diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/code_generators.cpp | 6 | ||||
-rw-r--r-- | src/flatc.cpp | 5 | ||||
-rw-r--r-- | src/flatc_main.cpp | 19 | ||||
-rw-r--r-- | src/flathash.cpp | 4 | ||||
-rw-r--r-- | src/idl_gen_cpp.cpp | 35 | ||||
-rw-r--r-- | src/idl_gen_dart.cpp | 32 | ||||
-rw-r--r-- | src/idl_gen_general.cpp | 211 | ||||
-rw-r--r-- | src/idl_gen_go.cpp | 127 | ||||
-rw-r--r-- | src/idl_gen_grpc.cpp | 30 | ||||
-rw-r--r-- | src/idl_gen_js_ts.cpp | 77 | ||||
-rw-r--r-- | src/idl_gen_json_schema.cpp | 1 | ||||
-rw-r--r-- | src/idl_gen_kotlin.cpp | 2448 | ||||
-rw-r--r-- | src/idl_gen_lobster.cpp | 90 | ||||
-rw-r--r-- | src/idl_gen_lua.cpp | 1248 | ||||
-rw-r--r-- | src/idl_gen_php.cpp | 3 | ||||
-rw-r--r-- | src/idl_gen_python.cpp | 128 | ||||
-rw-r--r-- | src/idl_gen_rust.cpp | 579 | ||||
-rw-r--r-- | src/idl_gen_text.cpp | 26 | ||||
-rw-r--r-- | src/idl_parser.cpp | 304 | ||||
-rw-r--r-- | src/reflection.cpp | 45 | ||||
-rw-r--r-- | src/util.cpp | 6 |
21 files changed, 2638 insertions, 2786 deletions
diff --git a/src/code_generators.cpp b/src/code_generators.cpp index 52ca3056..a46c4b73 100644 --- a/src/code_generators.cpp +++ b/src/code_generators.cpp @@ -15,12 +15,14 @@ */ #include "flatbuffers/code_generators.h" + #include <assert.h> -#include "flatbuffers/base.h" -#include "flatbuffers/util.h" #include <cmath> +#include "flatbuffers/base.h" +#include "flatbuffers/util.h" + #if defined(_MSC_VER) # pragma warning(push) # pragma warning(disable : 4127) // C4127: conditional expression is constant diff --git a/src/flatc.cpp b/src/flatc.cpp index ab2b1faf..74f2e238 100644 --- a/src/flatc.cpp +++ b/src/flatc.cpp @@ -42,7 +42,7 @@ void FlatCompiler::LoadBinarySchema(flatbuffers::Parser &parser, const std::string &filename, const std::string &contents) { if (!parser.Deserialize(reinterpret_cast<const uint8_t *>(contents.c_str()), - contents.size())) { + contents.size())) { Error("failed to load binary schema: " + filename, false, false); } } @@ -402,7 +402,8 @@ int FlatCompiler::Compile(int argc, const char **argv) { "\" matches the schema, use --raw-binary to read this file" " anyway."); } else if (!flatbuffers::BufferHasIdentifier( - contents.c_str(), parser->file_identifier_.c_str(), opts.size_prefixed)) { + contents.c_str(), parser->file_identifier_.c_str(), + opts.size_prefixed)) { Error("binary \"" + filename + "\" does not have expected file_identifier \"" + parser->file_identifier_ + diff --git a/src/flatc_main.cpp b/src/flatc_main.cpp index 72bb4a2f..352c3145 100644 --- a/src/flatc_main.cpp +++ b/src/flatc_main.cpp @@ -61,13 +61,15 @@ int main(int argc, const char *argv[]) { flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateJSTS, "-s", "--js", "JavaScript", true, nullptr, flatbuffers::IDLOptions::kJs, - "Generate JavaScript code for tables/structs", flatbuffers::JSTSMakeRule }, + "Generate JavaScript code for tables/structs", + flatbuffers::JSTSMakeRule }, { flatbuffers::GenerateDart, "-d", "--dart", "Dart", true, nullptr, flatbuffers::IDLOptions::kDart, "Generate Dart classes for tables/structs", flatbuffers::DartMakeRule }, { flatbuffers::GenerateJSTS, "-T", "--ts", "TypeScript", true, nullptr, flatbuffers::IDLOptions::kTs, - "Generate TypeScript code for tables/structs", flatbuffers::JSTSMakeRule }, + "Generate TypeScript code for tables/structs", + flatbuffers::JSTSMakeRule }, { flatbuffers::GenerateGeneral, "-n", "--csharp", "C#", true, nullptr, flatbuffers::IDLOptions::kCSharp, "Generate C# classes for tables/structs", flatbuffers::GeneralMakeRule }, @@ -75,23 +77,22 @@ int main(int argc, const char *argv[]) { flatbuffers::IDLOptions::kPython, "Generate Python files for tables/structs", flatbuffers::GeneralMakeRule }, - { flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true, nullptr, - flatbuffers::IDLOptions::kLobster, + { flatbuffers::GenerateLobster, nullptr, "--lobster", "Lobster", true, + nullptr, flatbuffers::IDLOptions::kLobster, "Generate Lobster files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateLua, "-l", "--lua", "Lua", true, nullptr, - flatbuffers::IDLOptions::kLua, - "Generate Lua files for tables/structs", + flatbuffers::IDLOptions::kLua, "Generate Lua files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateRust, "-r", "--rust", "Rust", true, nullptr, - flatbuffers::IDLOptions::kRust, - "Generate Rust files for tables/structs", + flatbuffers::IDLOptions::kRust, "Generate Rust files for tables/structs", flatbuffers::RustMakeRule }, { flatbuffers::GeneratePhp, nullptr, "--php", "PHP", true, nullptr, flatbuffers::IDLOptions::kPhp, "Generate PHP files for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateKotlin, nullptr, "--kotlin", "Kotlin", true, nullptr, - flatbuffers::IDLOptions::kKotlin, "Generate Kotlin classes for tables/structs", + flatbuffers::IDLOptions::kKotlin, + "Generate Kotlin classes for tables/structs", flatbuffers::GeneralMakeRule }, { flatbuffers::GenerateJsonSchema, nullptr, "--jsonschema", "JsonSchema", true, nullptr, flatbuffers::IDLOptions::kJsonSchema, diff --git a/src/flathash.cpp b/src/flathash.cpp index bc3d2df2..1264f821 100644 --- a/src/flathash.cpp +++ b/src/flathash.cpp @@ -15,9 +15,11 @@ */ #include <stdio.h> + #include <iostream> #include <sstream> #include <string> + #include "flatbuffers/hash.h" enum OutputFormat { kDecimal, kHexadecimal, kHexadecimal0x }; @@ -35,7 +37,7 @@ int main(int argc, char *argv[]) { } printf(" 32 bit:\n"); size = sizeof(flatbuffers::kHashFunctions32) / - sizeof(flatbuffers::kHashFunctions32[0]); + sizeof(flatbuffers::kHashFunctions32[0]); for (size_t i = 0; i < size; ++i) { printf(" * %s\n", flatbuffers::kHashFunctions32[i].name); } diff --git a/src/idl_gen_cpp.cpp b/src/idl_gen_cpp.cpp index d7b3abb5..706732b0 100644 --- a/src/idl_gen_cpp.cpp +++ b/src/idl_gen_cpp.cpp @@ -16,13 +16,13 @@ // independent from idl_parser, since this code is not needed for most clients +#include <unordered_set> + #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { // Pedantic warning free version of toupper(). @@ -208,9 +208,7 @@ class CppGenerator : public BaseGenerator { for (std::size_t i = 0; i < parser_.opts.cpp_includes.size(); ++i) { code_ += "#include \"" + parser_.opts.cpp_includes[i] + "\""; } - if (!parser_.opts.cpp_includes.empty()) { - code_ += ""; - } + if (!parser_.opts.cpp_includes.empty()) { code_ += ""; } } std::string EscapeKeyword(const std::string &name) const { @@ -577,7 +575,9 @@ class CppGenerator : public BaseGenerator { } case BASE_TYPE_UNION: // fall through - default: { return "void"; } + default: { + return "void"; + } } } @@ -696,7 +696,9 @@ class CppGenerator : public BaseGenerator { case BASE_TYPE_UNION: { return type.enum_def->name + "Union"; } - default: { return GenTypeBasic(type, true); } + default: { + return GenTypeBasic(type, true); + } } } @@ -1163,7 +1165,8 @@ class CppGenerator : public BaseGenerator { code_ += " void Set(T&& val) {"; code_ += " using RT = typename std::remove_reference<T>::type;"; code_ += " Reset();"; - code_ += " type = {{NAME}}Traits<typename RT::TableType>::enum_value;"; + code_ += + " type = {{NAME}}Traits<typename RT::TableType>::enum_value;"; code_ += " if (type != {{NONE}}) {"; code_ += " value = new RT(std::forward<T>(val));"; code_ += " }"; @@ -1276,7 +1279,8 @@ class CppGenerator : public BaseGenerator { " auto ptr = reinterpret_cast<const {{TYPE}} *>(obj);"; if (ev.union_type.base_type == BASE_TYPE_STRUCT) { if (ev.union_type.struct_def->fixed) { - code_ += " return verifier.Verify<{{TYPE}}>(static_cast<const " + code_ += + " return verifier.Verify<{{TYPE}}>(static_cast<const " "uint8_t *>(obj), 0);"; } else { code_ += getptr; @@ -1295,7 +1299,7 @@ class CppGenerator : public BaseGenerator { code_ += " }"; } } - code_ += " default: return true;"; // unknown values are OK. + code_ += " default: return true;"; // unknown values are OK. code_ += " }"; code_ += "}"; code_ += ""; @@ -1763,7 +1767,9 @@ class CppGenerator : public BaseGenerator { } break; } - default: { break; } + default: { + break; + } } } @@ -1925,7 +1931,8 @@ class CppGenerator : public BaseGenerator { } } - if (parser_.opts.mutable_buffer && !(is_scalar && IsUnion(field.value.type))) { + if (parser_.opts.mutable_buffer && + !(is_scalar && IsUnion(field.value.type))) { if (is_scalar) { const auto type = GenTypeWire(field.value.type, "", false); code_.SetValue("SET_FN", "SetField<" + type + ">"); @@ -2901,8 +2908,8 @@ class CppGenerator : public BaseGenerator { } else if (IsArray(field.value.type)) { auto underlying = GenTypeGet(field.value.type, "", "", "", false); code_ += " flatbuffers::Array<" + mut_field_type + ", " + - NumToString(field.value.type.fixed_length) + - "> *" + "mutable_{{FIELD_NAME}}() {"; + NumToString(field.value.type.fixed_length) + "> *" + + "mutable_{{FIELD_NAME}}() {"; code_ += " return reinterpret_cast<flatbuffers::Array<" + mut_field_type + ", " + NumToString(field.value.type.fixed_length) + diff --git a/src/idl_gen_dart.cpp b/src/idl_gen_dart.cpp index b97d4ea2..ab9425f8 100644 --- a/src/idl_gen_dart.cpp +++ b/src/idl_gen_dart.cpp @@ -71,9 +71,7 @@ class DartGenerator : public BaseGenerator { "// ignore_for_file: unused_import, unused_field, " "unused_local_variable\n\n"; - if (!kv->first.empty()) { - code += "library " + kv->first + ";\n\n"; - } + if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; } code += "import 'dart:typed_data' show Uint8List;\n"; code += "import 'package:flat_buffers/flat_buffers.dart' as " + _kFb + @@ -87,16 +85,20 @@ class DartGenerator : public BaseGenerator { ++kv2) { if (kv2->first != kv->first) { code += "import '" + - GeneratedFileName("./", file_name_ + (!kv2->first.empty() ? "_" + kv2->first : "")) + + GeneratedFileName( + "./", file_name_ + + (!kv2->first.empty() ? "_" + kv2->first : "")) + "' as " + ImportAliasName(kv2->first) + ";\n"; } } code += "\n"; code += kv->second; - if (!SaveFile( - GeneratedFileName(path_, file_name_ + (!kv->first.empty() ? "_" + kv->first : "")).c_str(), - code, false)) { + if (!SaveFile(GeneratedFileName( + path_, file_name_ + + (!kv->first.empty() ? "_" + kv->first : "")) + .c_str(), + code, false)) { return false; } } @@ -117,9 +119,7 @@ class DartGenerator : public BaseGenerator { } static std::string BuildNamespaceName(const Namespace &ns) { - if (ns.components.empty()) { - return ""; - } + if (ns.components.empty()) { return ""; } std::stringstream sstream; std::copy(ns.components.begin(), ns.components.end() - 1, std::ostream_iterator<std::string>(sstream, ".")); @@ -139,7 +139,8 @@ class DartGenerator : public BaseGenerator { return ret; } - void GenIncludeDependencies(std::string* code, const std::string& the_namespace) { + void GenIncludeDependencies(std::string *code, + const std::string &the_namespace) { for (auto it = parser_.included_files_.begin(); it != parser_.included_files_.end(); ++it) { if (it->second.empty()) continue; @@ -147,7 +148,11 @@ class DartGenerator : public BaseGenerator { auto noext = flatbuffers::StripExtension(it->second); auto basename = flatbuffers::StripPath(noext); - *code += "import '" + GeneratedFileName("", basename + (the_namespace == "" ? "" : "_" + the_namespace)) + "';\n"; + *code += + "import '" + + GeneratedFileName( + "", basename + (the_namespace == "" ? "" : "_" + the_namespace)) + + "';\n"; } } @@ -798,7 +803,8 @@ class DartGenerator : public BaseGenerator { } code += "\n : null;\n"; } else if (field.value.type.base_type == BASE_TYPE_STRING) { - code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + ");\n"; + code += " = fbBuilder.writeString(_" + MakeCamel(field.name, false) + + ");\n"; } else { code += " = _" + MakeCamel(field.name, false) + "?.getOrCreateOffset(fbBuilder);\n"; diff --git a/src/idl_gen_general.cpp b/src/idl_gen_general.cpp index bb2920f5..48ec2b73 100644 --- a/src/idl_gen_general.cpp +++ b/src/idl_gen_general.cpp @@ -69,75 +69,71 @@ const LanguageParameters &GetLangParams(IDLOptions::Language lang) { "Double.", "Float.", "NaN", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"); static const LanguageParameters language_parameters[] = { - { - IDLOptions::kJava, - false, - ".java", - "String", - "boolean ", - " {\n", - "class ", - " final ", - "final ", - "final class ", - ";\n", - "()", - "", - " extends ", - "package ", - ";", - "", - "_bb.order(ByteOrder.LITTLE_ENDIAN); ", - "position()", - "offset()", - "", - "", - "", - "import java.nio.*;\nimport java.lang.*;\nimport " - "java.util.*;\nimport com.google.flatbuffers.*;\n", - "\n@SuppressWarnings(\"unused\")\n", - "\n@javax.annotation.Generated(value=\"flatc\")\n", - { - "/**", - " *", - " */", - }, - &JavaFloatGen - }, - { - IDLOptions::kCSharp, - true, - ".cs", - "string", - "bool ", - "\n{\n", - "struct ", - " readonly ", - "", - "enum ", - ",\n", - " { get", - "} ", - " : ", - "namespace ", - "\n{", - "\n}\n", - "", - "Position", - "Offset", - "__p.", - "Table.", - "?", - "using global::System;\nusing global::FlatBuffers;\n\n", - "", - "", - { - nullptr, - "///", - nullptr, - }, - &CSharpFloatGen - }, + { IDLOptions::kJava, + false, + ".java", + "String", + "boolean ", + " {\n", + "class ", + " final ", + "final ", + "final class ", + ";\n", + "()", + "", + " extends ", + "package ", + ";", + "", + "_bb.order(ByteOrder.LITTLE_ENDIAN); ", + "position()", + "offset()", + "", + "", + "", + "import java.nio.*;\nimport java.lang.*;\nimport " + "java.util.*;\nimport com.google.flatbuffers.*;\n", + "\n@SuppressWarnings(\"unused\")\n", + "\n@javax.annotation.Generated(value=\"flatc\")\n", + { + "/**", + " *", + " */", + }, + &JavaFloatGen }, + { IDLOptions::kCSharp, + true, + ".cs", + "string", + "bool ", + "\n{\n", + "struct ", + " readonly ", + "", + "enum ", + ",\n", + " { get", + "} ", + " : ", + "namespace ", + "\n{", + "\n}\n", + "", + "Position", + "Offset", + "__p.", + "Table.", + "?", + "using global::System;\nusing global::FlatBuffers;\n\n", + "", + "", + { + nullptr, + "///", + nullptr, + }, + &CSharpFloatGen }, }; if (lang == IDLOptions::kJava) { @@ -233,9 +229,7 @@ class GeneralGenerator : public BaseGenerator { } code += lang_.class_annotation; } - if (parser_.opts.gen_generated) { - code += lang_.generated_type_annotation; - } + if (parser_.opts.gen_generated) { code += lang_.generated_type_annotation; } code += classcode; if (!namespace_name.empty()) code += lang_.namespace_end; auto filename = NamespaceDir(ns) + defname + lang_.file_extension; @@ -339,7 +333,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_ARRAY: case BASE_TYPE_VECTOR: if (vectorelem) return DestinationType(type.VectorType(), vectorelem); - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: return type; } } @@ -383,7 +377,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_UINT: return " & 0xFFFFFFFFL"; case BASE_TYPE_VECTOR: if (vectorelem) return DestinationMask(type.VectorType(), vectorelem); - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: return ""; } } @@ -440,7 +434,9 @@ class GeneralGenerator : public BaseGenerator { return ""; } - std::string SourceCast(const Type &type) const { return SourceCast(type, true); } + std::string SourceCast(const Type &type) const { + return SourceCast(type, true); + } std::string SourceCastBasic(const Type &type, bool castFromDest) const { return IsScalar(type.base_type) ? SourceCast(type, castFromDest) : ""; @@ -459,8 +455,9 @@ class GeneralGenerator : public BaseGenerator { : value.constant; } - std::string GenDefaultValue(const FieldDef &field, bool enableLangOverrides) const { - auto& value = field.value; + std::string GenDefaultValue(const FieldDef &field, + bool enableLangOverrides) const { + auto &value = field.value; if (enableLangOverrides) { // handles both enum case and vector of enum case if (lang_.language == IDLOptions::kCSharp && @@ -482,7 +479,7 @@ class GeneralGenerator : public BaseGenerator { case BASE_TYPE_UINT: case BASE_TYPE_LONG: return value.constant + longSuffix; default: - if(IsFloat(value.type.base_type)) + if (IsFloat(value.type.base_type)) return lang_.float_gen->GenFloatConstant(field); else return value.constant; @@ -495,7 +492,7 @@ class GeneralGenerator : public BaseGenerator { std::string GenDefaultValueBasic(const FieldDef &field, bool enableLangOverrides) const { - auto& value = field.value; + auto &value = field.value; if (!IsScalar(value.type.base_type)) { if (enableLangOverrides) { if (lang_.language == IDLOptions::kCSharp) { @@ -530,15 +527,14 @@ class GeneralGenerator : public BaseGenerator { GenComment(enum_def.doc_comment, code_ptr, &lang_.comment_config); // In C# this indicates enumeration values can be treated as bit flags. - if (lang_.language == IDLOptions::kCSharp && enum_def.attributes.Lookup("bit_flags")) { + if (lang_.language == IDLOptions::kCSharp && + enum_def.attributes.Lookup("bit_flags")) { code += "[System.FlagsAttribute]\n"; } if (enum_def.attributes.Lookup("private")) { // For Java, we leave the enum unmarked to indicate package-private // For C# we mark the enum as internal - if (lang_.language == IDLOptions::kCSharp) { - code += "internal "; - } + if (lang_.language == IDLOptions::kCSharp) { code += "internal "; } } else { code += "public "; } @@ -870,9 +866,7 @@ class GeneralGenerator : public BaseGenerator { if (struct_def.attributes.Lookup("private")) { // For Java, we leave the struct unmarked to indicate package-private // For C# we mark the struct as internal - if (lang_.language == IDLOptions::kCSharp) { - code += "internal "; - } + if (lang_.language == IDLOptions::kCSharp) { code += "internal "; } } else { code += "public "; } @@ -1016,8 +1010,8 @@ class GeneralGenerator : public BaseGenerator { code += "(new " + type_name + "(), j); }\n"; } } else if (field.value.type.base_type == BASE_TYPE_UNION || - (field.value.type.base_type == BASE_TYPE_VECTOR && - field.value.type.VectorType().base_type == BASE_TYPE_UNION)) { + (field.value.type.base_type == BASE_TYPE_VECTOR && + field.value.type.VectorType().base_type == BASE_TYPE_UNION)) { if (lang_.language == IDLOptions::kCSharp) { // Union types in C# use generic Table-derived type for better type // safety. @@ -1092,8 +1086,8 @@ class GeneralGenerator : public BaseGenerator { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_UNION && lang_.language == IDLOptions::kCSharp) { - conditional_cast = "(TTable?)"; - getter += "<TTable>"; + conditional_cast = "(TTable?)"; + getter += "<TTable>"; } code += "("; if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -1145,7 +1139,8 @@ class GeneralGenerator : public BaseGenerator { if (lang_.language == IDLOptions::kCSharp) { code += "() where TTable : struct, IFlatbufferObject"; code += offset_prefix + "(TTable?)" + getter; - code += "<TTable>(o + " + lang_.accessor_prefix + "bb_pos) : null"; + code += + "<TTable>(o + " + lang_.accessor_prefix + "bb_pos) : null"; } else { code += "(" + type_name + " obj)" + offset_prefix + getter; code += "(obj, o + " + lang_.accessor_prefix + "bb_pos) : null"; @@ -1174,19 +1169,21 @@ class GeneralGenerator : public BaseGenerator { auto &key_field = **kit; if (key_field.key) { auto qualified_name = WrapInNameSpace(sd); - code += " public " + qualified_name + lang_.optional_suffix + " "; + code += + " public " + qualified_name + lang_.optional_suffix + " "; code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; code += GenTypeNameDest(key_field.value.type) + " key)"; code += offset_prefix; code += qualified_name + ".__lookup_by_key("; - if (lang_.language == IDLOptions::kJava) - code += "null, "; + if (lang_.language == IDLOptions::kJava) code += "null, "; code += lang_.accessor_prefix + "__vector(o), key, "; code += lang_.accessor_prefix + "bb) : null; "; code += "}\n"; if (lang_.language == IDLOptions::kJava) { - code += " public " + qualified_name + lang_.optional_suffix + " "; - code += MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; + code += + " public " + qualified_name + lang_.optional_suffix + " "; + code += + MakeCamel(field.name, lang_.first_camel_upper) + "ByKey("; code += qualified_name + lang_.optional_suffix + " obj, "; code += GenTypeNameDest(key_field.value.type) + " key)"; code += offset_prefix; @@ -1259,12 +1256,15 @@ class GeneralGenerator : public BaseGenerator { break; case IDLOptions::kCSharp: code += "#if ENABLE_SPAN_T\n"; - code += " public Span<" + GenTypeBasic(field.value.type.VectorType()) + "> Get"; + code += " public Span<" + + GenTypeBasic(field.value.type.VectorType()) + "> Get"; code += MakeCamel(field.name, lang_.first_camel_upper); code += "Bytes() { return "; - code += lang_.accessor_prefix + "__vector_as_span<"+ GenTypeBasic(field.value.type.VectorType()) +">("; + code += lang_.accessor_prefix + "__vector_as_span<" + + GenTypeBasic(field.value.type.VectorType()) + ">("; code += NumToString(field.value.offset); - code += ", " + NumToString(SizeOf(field.value.type.VectorType().base_type)); + code += ", " + NumToString( + SizeOf(field.value.type.VectorType().base_type)); code += "); }\n"; code += "#else\n"; code += " public ArraySegment<byte>? Get"; @@ -1596,10 +1596,10 @@ class GeneralGenerator : public BaseGenerator { std::string size_prefix[] = { "", "SizePrefixed" }; for (int i = 0; i < 2; ++i) { code += " public static void "; - code += FunctionStart('F') + "inish" + size_prefix[i] + - struct_def.name; - code += "Buffer(FlatBufferBuilder builder, " + - GenOffsetType(struct_def); + code += + FunctionStart('F') + "inish" + size_prefix[i] + struct_def.name; + code += + "Buffer(FlatBufferBuilder builder, " + GenOffsetType(struct_def); code += " offset) {"; code += " builder." + FunctionStart('F') + "inish" + size_prefix[i] + "(offset"; @@ -1636,7 +1636,7 @@ class GeneralGenerator : public BaseGenerator { code += "\n public static " + struct_def.name + lang_.optional_suffix; code += " __lookup_by_key("; if (lang_.language == IDLOptions::kJava) - code += struct_def.name + " obj, "; + code += struct_def.name + " obj, "; code += "int vectorLocation, "; code += GenTypeNameDest(key_field->value.type); code += " key, ByteBuffer bb) {\n"; @@ -1684,8 +1684,7 @@ class GeneralGenerator : public BaseGenerator { // Generate a vector of structs accessor class. code += "\n"; code += " "; - if (!struct_def.attributes.Lookup("private")) - code += "public "; + if (!struct_def.attributes.Lookup("private")) code += "public "; code += "static "; code += lang_.unsubclassable_decl; code += lang_.accessor_type + "Vector" + lang_.inheritance_marker; diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp index aa25751d..4ed1a80b 100644 --- a/src/idl_gen_go.cpp +++ b/src/idl_gen_go.cpp @@ -43,7 +43,7 @@ static std::string GeneratedFileName(const std::string &path, namespace go { // see https://golang.org/ref/spec#Keywords -static const char * const g_golang_keywords[] = { +static const char *const g_golang_keywords[] = { "break", "default", "func", "interface", "select", "case", "defer", "go", "map", "struct", "chan", "else", "goto", "package", "switch", "const", "fallthrough", "if", "range", "type", "continue", @@ -151,7 +151,8 @@ class GoGenerator : public BaseGenerator { // Construct the name of the type for this enum. std::string GetEnumTypeName(const EnumDef &enum_def) { - return WrapInNameSpaceAndTrack(enum_def.defined_namespace, GoIdentity(enum_def.name)); + return WrapInNameSpaceAndTrack(enum_def.defined_namespace, + GoIdentity(enum_def.name)); } // Create a type for the enum values. @@ -222,7 +223,7 @@ class GoGenerator : public BaseGenerator { code += "\tif s, ok := EnumNames" + enum_def.name + "[v]; ok {\n"; code += "\t\treturn s\n"; code += "\t}\n"; - code += "\treturn \""+ enum_def.name; + code += "\treturn \"" + enum_def.name; code += "(\" + strconv.FormatInt(int64(v), 10) + \")\"\n"; code += "}\n\n"; } @@ -325,23 +326,21 @@ class GoGenerator : public BaseGenerator { // Get the value of a struct's scalar. void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); GenReceiver(struct_def, code_ptr); code += " " + MakeCamel(field.name); code += "() " + TypeName(field) + " {\n"; - code += "\treturn " + CastToEnum( - field.value.type, - getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" + - NumToString(field.value.offset) + "))"); + code += "\treturn " + + CastToEnum(field.value.type, + getter + "(rcv._tab.Pos + flatbuffers.UOffsetT(" + + NumToString(field.value.offset) + "))"); code += "\n}\n"; } // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); @@ -358,8 +357,7 @@ class GoGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Struct. void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); code += " " + MakeCamel(field.name); @@ -377,8 +375,7 @@ class GoGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -400,8 +397,7 @@ class GoGenerator : public BaseGenerator { } // Get the value of a string. - void GetStringField(const StructDef &struct_def, - const FieldDef &field, + void GetStringField(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -428,8 +424,7 @@ class GoGenerator : public BaseGenerator { // Get the value of a vector's struct member. void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; auto vectortype = field.value.type.VectorType(); @@ -461,10 +456,11 @@ class GoGenerator : public BaseGenerator { code += "(j int) " + TypeName(field) + " "; code += OffsetPrefix(field); code += "\t\ta := rcv._tab.Vector(o)\n"; - code += "\t\treturn " + CastToEnum( - field.value.type, - GenGetter(field.value.type) + "(a + flatbuffers.UOffsetT(j*" + - NumToString(InlineSize(vectortype)) + "))"); + code += "\t\treturn " + + CastToEnum(field.value.type, + GenGetter(field.value.type) + + "(a + flatbuffers.UOffsetT(j*" + + NumToString(InlineSize(vectortype)) + "))"); code += "\n\t}\n"; if (vectortype.base_type == BASE_TYPE_STRING) { code += "\treturn nil\n"; @@ -518,8 +514,8 @@ class GoGenerator : public BaseGenerator { // Recursively generate struct construction statements and instert manual // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { std::string &code = *code_ptr; code += "\tbuilder.Prep(" + NumToString(struct_def.minalign) + ", "; code += NumToString(struct_def.bytesize) + ")\n"; @@ -533,7 +529,9 @@ class GoGenerator : public BaseGenerator { (nameprefix + (field.name + "_")).c_str(), code_ptr); } else { code += "\tbuilder.Prepend" + GenMethod(field) + "("; - code += CastToBaseType(field.value.type, nameprefix + GoIdentity(field.name)) + ")\n"; + code += CastToBaseType(field.value.type, + nameprefix + GoIdentity(field.name)) + + ")\n"; } } } @@ -582,8 +580,8 @@ class GoGenerator : public BaseGenerator { } // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func " + struct_def.name + "Start"; code += MakeCamel(field.name); @@ -612,8 +610,8 @@ class GoGenerator : public BaseGenerator { } // Generate a struct field getter, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, nullptr, ""); if (IsScalar(field.value.type.base_type)) { if (struct_def.fixed) { @@ -630,7 +628,9 @@ class GoGenerator : public BaseGenerator { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -652,10 +652,9 @@ class GoGenerator : public BaseGenerator { } } - // Mutate the value of a struct's scalar. + // Mutate the value of a struct's scalar. void MutateScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string type = MakeCamel(GenTypeBasic(field.value.type)); std::string setter = "rcv._tab.Mutate" + type; @@ -669,8 +668,7 @@ class GoGenerator : public BaseGenerator { // Mutate the value of a table's scalar. void MutateScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string type = MakeCamel(GenTypeBasic(field.value.type)); std::string setter = "rcv._tab.Mutate" + type + "Slot"; @@ -916,9 +914,9 @@ class GoGenerator : public BaseGenerator { if (IsScalar(field.value.type.element)) { code += "\t\t\tbuilder.Prepend" + MakeCamel(GenTypeBasic(field.value.type.VectorType())) + "(" + - CastToBaseType( - field.value.type.VectorType(), - "t." + MakeCamel(field.name) + "[j]") + ")\n"; + CastToBaseType(field.value.type.VectorType(), + "t." + MakeCamel(field.name) + "[j]") + + ")\n"; } else if (field.value.type.element == BASE_TYPE_STRUCT && field.value.type.struct_def->fixed) { code += "\t\t\t" + @@ -979,8 +977,8 @@ class GoGenerator : public BaseGenerator { code += "}\n\n"; } - void GenNativeTableUnPack( - const StructDef &struct_def, std::string *code_ptr) { + void GenNativeTableUnPack(const StructDef &struct_def, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" + @@ -995,8 +993,8 @@ class GoGenerator : public BaseGenerator { if (field.value.type.enum_def != nullptr && field.value.type.enum_def->is_union) continue; - code += "\tt." + field_name_camel + " = rcv." + field_name_camel + - "()\n"; + code += + "\tt." + field_name_camel + " = rcv." + field_name_camel + "()\n"; } else if (field.value.type.base_type == BASE_TYPE_STRING) { code += "\tt." + field_name_camel + " = string(rcv." + field_name_camel + "())\n"; @@ -1084,8 +1082,8 @@ class GoGenerator : public BaseGenerator { } } - void GenNativeStructUnPack( - const StructDef &struct_def, std::string *code_ptr) { + void GenNativeStructUnPack(const StructDef &struct_def, + std::string *code_ptr) { std::string &code = *code_ptr; code += "func (rcv *" + struct_def.name + ") UnPackTo(t *" + @@ -1137,8 +1135,7 @@ class GoGenerator : public BaseGenerator { EndEnumNames(code_ptr); BeginEnumValues(enum_def, code_ptr); - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { auto &ev = **it; EnumValueMember(enum_def, ev, max_name_length, code_ptr); } @@ -1189,9 +1186,7 @@ class GoGenerator : public BaseGenerator { } std::string GenTypeGet(const Type &type) { - if (type.enum_def != nullptr) { - return GetEnumTypeName(*type.enum_def); - } + if (type.enum_def != nullptr) { return GetEnumTypeName(*type.enum_def); } return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); } @@ -1221,7 +1216,8 @@ class GoGenerator : public BaseGenerator { std::string GenConstant(const FieldDef &field) { switch (field.value.type.base_type) { - case BASE_TYPE_BOOL: return field.value.constant == "0" ? "false" : "true"; + case BASE_TYPE_BOOL: + return field.value.constant == "0" ? "false" : "true"; default: return field.value.constant; } } @@ -1248,11 +1244,11 @@ class GoGenerator : public BaseGenerator { } else if (type.base_type == BASE_TYPE_VECTOR) { return "[]" + NativeType(type.VectorType()); } else if (type.base_type == BASE_TYPE_STRUCT) { - return "*" + WrapInNameSpaceAndTrack( - type.struct_def->defined_namespace, NativeName(*type.struct_def)); + return "*" + WrapInNameSpaceAndTrack(type.struct_def->defined_namespace, + NativeName(*type.struct_def)); } else if (type.base_type == BASE_TYPE_UNION) { - return "*" + WrapInNameSpaceAndTrack( - type.enum_def->defined_namespace, NativeName(*type.enum_def)); + return "*" + WrapInNameSpaceAndTrack(type.enum_def->defined_namespace, + NativeName(*type.enum_def)); } FLATBUFFERS_ASSERT(0); return std::string(); @@ -1271,13 +1267,12 @@ class GoGenerator : public BaseGenerator { void BeginFile(const std::string &name_space_name, const bool needs_imports, const bool is_enum, std::string *code_ptr) { std::string &code = *code_ptr; - code = code + "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n"; + code = code + + "// Code generated by the FlatBuffers compiler. DO NOT EDIT.\n\n"; code += "package " + name_space_name + "\n\n"; if (needs_imports) { code += "import (\n"; - if (is_enum) { - code += "\t\"strconv\"\n\n"; - } + if (is_enum) { code += "\t\"strconv\"\n\n"; } if (!parser_.opts.go_import.empty()) { code += "\tflatbuffers \"" + parser_.opts.go_import + "\"\n"; } else { @@ -1286,17 +1281,14 @@ class GoGenerator : public BaseGenerator { if (tracked_imported_namespaces_.size() > 0) { code += "\n"; for (auto it = tracked_imported_namespaces_.begin(); - it != tracked_imported_namespaces_.end(); - ++it) { - code += "\t" + NamespaceImportName(*it) + " \"" + \ - NamespaceImportPath(*it) + "\"\n"; + it != tracked_imported_namespaces_.end(); ++it) { + code += "\t" + NamespaceImportName(*it) + " \"" + + NamespaceImportPath(*it) + "\"\n"; } } code += ")\n\n"; } else { - if (is_enum) { - code += "import \"strconv\"\n\n"; - } + if (is_enum) { code += "import \"strconv\"\n\n"; } } } @@ -1364,8 +1356,7 @@ class GoGenerator : public BaseGenerator { static size_t MaxNameLength(const EnumDef &enum_def) { size_t max = 0; - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { max = std::max((*it)->name.length(), max); } return max; diff --git a/src/idl_gen_grpc.cpp b/src/idl_gen_grpc.cpp index 1d5e8e5e..ec129902 100644 --- a/src/idl_gen_grpc.cpp +++ b/src/idl_gen_grpc.cpp @@ -20,7 +20,6 @@ #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" - #include "src/compiler/cpp_generator.h" #include "src/compiler/go_generator.h" #include "src/compiler/java_generator.h" @@ -35,9 +34,7 @@ namespace flatbuffers { class FlatBufMethod : public grpc_generator::Method { public: - enum Streaming { - kNone, kClient, kServer, kBiDi - }; + enum Streaming { kNone, kClient, kServer, kBiDi }; FlatBufMethod(const RPCCall *method) : method_(method) { streaming_ = kNone; @@ -171,7 +168,7 @@ class FlatBufPrinter : public grpc_generator::Printer { void Outdent() { indent_--; - FLATBUFFERS_ASSERT(indent_ >= 0); + FLATBUFFERS_ASSERT(indent_ >= 0); } private: @@ -182,9 +179,7 @@ class FlatBufPrinter : public grpc_generator::Printer { class FlatBufFile : public grpc_generator::File { public: - enum Language { - kLanguageGo, kLanguageCpp, kLanguageJava - }; + enum Language { kLanguageGo, kLanguageCpp, kLanguageJava }; FlatBufFile(const Parser &parser, const std::string &file_name, Language language) @@ -270,7 +265,8 @@ class GoGRPCGenerator : public flatbuffers::BaseGenerator { auto service = file.service(i); const Definition *def = parser_.services_.vec[i]; p.package_name = LastNamespacePart(*(def->defined_namespace)); - p.service_prefix = def->defined_namespace->GetFullyQualifiedName(""); // file.package(); + p.service_prefix = + def->defined_namespace->GetFullyQualifiedName(""); // file.package(); std::string output = grpc_go_generator::GenerateServiceSource(&file, service.get(), &p); std::string filename = @@ -313,20 +309,20 @@ bool GenerateCppGRPC(const Parser &parser, const std::string &path, std::string header_code = grpc_cpp_generator::GetHeaderPrologue(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderIncludes(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderServices(&fbfile, generator_parameters) + - grpc_cpp_generator::GetHeaderEpilogue(&fbfile, generator_parameters); + grpc_cpp_generator::GetHeaderIncludes(&fbfile, generator_parameters) + + grpc_cpp_generator::GetHeaderServices(&fbfile, generator_parameters) + + grpc_cpp_generator::GetHeaderEpilogue(&fbfile, generator_parameters); std::string source_code = grpc_cpp_generator::GetSourcePrologue(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceIncludes(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) + - grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters); + grpc_cpp_generator::GetSourceIncludes(&fbfile, generator_parameters) + + grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) + + grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters); return flatbuffers::SaveFile((path + file_name + ".grpc.fb.h").c_str(), header_code, false) && - flatbuffers::SaveFile((path + file_name + ".grpc.fb.cc").c_str(), - source_code, false); + flatbuffers::SaveFile((path + file_name + ".grpc.fb.cc").c_str(), + source_code, false); } class JavaGRPCGenerator : public flatbuffers::BaseGenerator { diff --git a/src/idl_gen_js_ts.cpp b/src/idl_gen_js_ts.cpp index 84dc7374..8d86d302 100644 --- a/src/idl_gen_js_ts.cpp +++ b/src/idl_gen_js_ts.cpp @@ -127,9 +127,7 @@ class JsTsGenerator : public BaseGenerator { const auto &file = *it; const auto basename = flatbuffers::StripPath(flatbuffers::StripExtension(file)); - if (basename != file_name_) { - code += GenPrefixedImport(file, basename); - } + if (basename != file_name_) { code += GenPrefixedImport(file, basename); } } } @@ -309,14 +307,12 @@ class JsTsGenerator : public BaseGenerator { result += " " + type_name; break; } - default: { result += " {" + type_name + "}"; } - } - if (!arg_name.empty()) { - result += " " + arg_name; - } - if (include_newline) { - result += "\n"; + default: { + result += " {" + type_name + "}"; + } } + if (!arg_name.empty()) { result += " " + arg_name; } + if (include_newline) { result += "\n"; } return result; } @@ -605,7 +601,8 @@ class JsTsGenerator : public BaseGenerator { } void GenerateRootAccessor(StructDef &struct_def, std::string *code_ptr, - std::string &code, std::string &object_name, bool size_prefixed) { + std::string &code, std::string &object_name, + bool size_prefixed) { if (!struct_def.fixed) { GenDocComment(code_ptr, GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + @@ -613,11 +610,13 @@ class JsTsGenerator : public BaseGenerator { GenTypeAnnotation(kReturns, object_name, "", false)); std::string sizePrefixed("SizePrefixed"); if (lang_.language == IDLOptions::kTs) { - code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As"); + code += "static get" + (size_prefixed ? sizePrefixed : "") + "Root" + + Verbose(struct_def, "As"); code += "(bb:flatbuffers.ByteBuffer, obj?:" + object_name + "):" + object_name + " {\n"; } else { - code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") + "Root" + Verbose(struct_def, "As"); + code += object_name + ".get" + (size_prefixed ? sizePrefixed : "") + + "Root" + Verbose(struct_def, "As"); code += " = function(bb, obj) {\n"; } code += " return (obj || new " + object_name; @@ -627,21 +626,22 @@ class JsTsGenerator : public BaseGenerator { } void GenerateFinisher(StructDef &struct_def, std::string *code_ptr, - std::string &code, std::string &object_name, bool size_prefixed) { + std::string &code, std::string &object_name, + bool size_prefixed) { if (parser_.root_struct_def_ == &struct_def) { std::string sizePrefixed("SizePrefixed"); GenDocComment( code_ptr, GenTypeAnnotation(kParam, "flatbuffers.Builder", "builder") + - GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", - false)); + GenTypeAnnotation(kParam, "flatbuffers.Offset", "offset", false)); if (lang_.language == IDLOptions::kTs) { - code += "static finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer"; - code += - "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n"; + code += "static finish" + (size_prefixed ? sizePrefixed : "") + + Verbose(struct_def) + "Buffer"; + code += "(builder:flatbuffers.Builder, offset:flatbuffers.Offset) {\n"; } else { - code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") + Verbose(struct_def) + "Buffer"; + code += object_name + ".finish" + (size_prefixed ? sizePrefixed : "") + + Verbose(struct_def) + "Buffer"; code += " = function(builder, offset) {\n"; } @@ -650,9 +650,7 @@ class JsTsGenerator : public BaseGenerator { code += ", '" + parser_.file_identifier_ + "'"; } if (size_prefixed) { - if (parser_.file_identifier_.empty()) { - code += ", undefined"; - } + if (parser_.file_identifier_.empty()) { code += ", undefined"; } code += ", true"; } code += ");\n"; @@ -682,7 +680,8 @@ class JsTsGenerator : public BaseGenerator { code += " {\n"; if (lang_.language != IDLOptions::kTs) { code += " /**\n"; - code += " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", ""); + code += + " * " + GenTypeAnnotation(kType, "flatbuffers.ByteBuffer", ""); code += " */\n"; } code += " bb: flatbuffers.ByteBuffer|null = null;\n"; @@ -752,10 +751,9 @@ class JsTsGenerator : public BaseGenerator { // Generate the identifier check method if (!struct_def.fixed && parser_.root_struct_def_ == &struct_def && !parser_.file_identifier_.empty()) { - GenDocComment( - code_ptr, - GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + - GenTypeAnnotation(kReturns, "boolean", "", false)); + GenDocComment(code_ptr, + GenTypeAnnotation(kParam, "flatbuffers.ByteBuffer", "bb") + + GenTypeAnnotation(kReturns, "boolean", "", false)); if (lang_.language == IDLOptions::kTs) { code += "static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean " @@ -872,7 +870,8 @@ class JsTsGenerator : public BaseGenerator { code += ", " + GenBBAccess() + ") : null;\n"; } - if (lang_.language == IDLOptions::kTs && !parser_.opts.generate_all) { + if (lang_.language == IDLOptions::kTs && + !parser_.opts.generate_all) { imported_files.insert(field.value.type.struct_def->file); } @@ -1290,8 +1289,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; paramDoc += GenTypeAnnotation(kParam, GetArgType(field), GetArgName(field)); } @@ -1311,8 +1309,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; if (lang_.language == IDLOptions::kTs) { code += ", " + GetArgName(field) + ":" + GetArgType(field); @@ -1336,8 +1333,7 @@ class JsTsGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) - continue; + if (field.deprecated) continue; code += " " + methodPrefix + ".add" + MakeCamel(field.name) + "("; code += "builder, " + GetArgName(field) + ");\n"; @@ -1346,14 +1342,11 @@ class JsTsGenerator : public BaseGenerator { code += " return " + methodPrefix + ".end" + Verbose(struct_def) + "(builder);\n"; code += "}\n"; - if (lang_.language == IDLOptions::kJs) - code += "\n"; + if (lang_.language == IDLOptions::kJs) code += "\n"; } if (lang_.language == IDLOptions::kTs) { - if (!object_namespace.empty()) { - code += "}\n"; - } + if (!object_namespace.empty()) { code += "}\n"; } code += "}\n"; } } @@ -1372,9 +1365,7 @@ class JsTsGenerator : public BaseGenerator { return argname; } - std::string Verbose(const StructDef &struct_def, - const char* prefix = "") - { + std::string Verbose(const StructDef &struct_def, const char *prefix = "") { return parser_.opts.js_ts_short_names ? "" : prefix + struct_def.name; } }; diff --git a/src/idl_gen_json_schema.cpp b/src/idl_gen_json_schema.cpp index 27e2cd46..5d7bad6d 100644 --- a/src/idl_gen_json_schema.cpp +++ b/src/idl_gen_json_schema.cpp @@ -15,6 +15,7 @@ */ #include <iostream> + #include "flatbuffers/code_generators.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" diff --git a/src/idl_gen_kotlin.cpp b/src/idl_gen_kotlin.cpp index d11599fe..b12e554d 100644 --- a/src/idl_gen_kotlin.cpp +++ b/src/idl_gen_kotlin.cpp @@ -18,12 +18,13 @@ #include <functional> #include <unordered_set> + #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" #if defined(FLATBUFFERS_CPP98_STL) -#include <cctype> +# include <cctype> #endif // defined(FLATBUFFERS_CPP98_STL) namespace flatbuffers { @@ -35,21 +36,20 @@ static TypedFloatConstantGenerator KotlinFloatGen("Double.", "Float.", "NaN", "POSITIVE_INFINITY", "NEGATIVE_INFINITY"); -static const CommentConfig comment_config = {"/**", " *", " */"}; +static const CommentConfig comment_config = { "/**", " *", " */" }; static const std::string ident_pad = " "; static const char *keywords[] = { - "package", "as", "typealias", "class", "this", "super", - "val", "var", "fun", "for", "null", "true", - "false", "is", "in", "throw", "return", "break", - "continue", "object", "if", "try", "else", "while", - "do", "when", "interface", "typeof", "Any", "Character"}; + "package", "as", "typealias", "class", "this", "super", + "val", "var", "fun", "for", "null", "true", + "false", "is", "in", "throw", "return", "break", + "continue", "object", "if", "try", "else", "while", + "do", "when", "interface", "typeof", "Any", "Character" +}; // Escape Keywords static std::string Esc(const std::string &name) { for (size_t i = 0; i < sizeof(keywords) / sizeof(keywords[0]); i++) { - if (name == keywords[i]) { - return MakeCamel(name + "_", false); - } + if (name == keywords[i]) { return MakeCamel(name + "_", false); } } return MakeCamel(name, false); @@ -145,1380 +145,1298 @@ class KotlinGenerator : public BaseGenerator { #KTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD - }; - return kotlin_typename[type]; + // clang-format on + }; + return kotlin_typename[type]; + } + std::string GenTypePointer(const Type &type) const { + switch (type.base_type) { + case BASE_TYPE_STRING: return "String"; + case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType()); + case BASE_TYPE_STRUCT: return WrapInNameSpace(*type.struct_def); + default: return "Table"; } + } - std::string GenTypePointer(const Type &type) const { - switch (type.base_type) { - case BASE_TYPE_STRING: - return "String"; - case BASE_TYPE_VECTOR: - return GenTypeGet(type.VectorType()); - case BASE_TYPE_STRUCT: - return WrapInNameSpace(*type.struct_def); - default: - return "Table"; - } - } + std::string GenTypeGet(const Type &type) const { + return IsScalar(type.base_type) ? GenTypeBasic(type.base_type) + : GenTypePointer(type); + } - std::string GenTypeGet(const Type &type) const { - return IsScalar(type.base_type) ? GenTypeBasic(type.base_type) - : GenTypePointer(type); - } + std::string GenEnumDefaultValue(const FieldDef &field) const { + auto &value = field.value; + FLATBUFFERS_ASSERT(value.type.enum_def); + auto &enum_def = *value.type.enum_def; + auto enum_val = enum_def.FindByValue(value.constant); + return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name) + : value.constant; + } - std::string GenEnumDefaultValue(const FieldDef &field) const { - auto &value = field.value; - FLATBUFFERS_ASSERT(value.type.enum_def); - auto &enum_def = *value.type.enum_def; - auto enum_val = enum_def.FindByValue(value.constant); - return enum_val ? (WrapInNameSpace(enum_def) + "." + enum_val->name) - : value.constant; + // Generate default values to compare against a default value when + // `force_defaults` is `false`. + // Main differences are: + // - Floats are upcasted to doubles + // - Unsigned are casted to signed + std::string GenFBBDefaultValue(const FieldDef &field) const { + auto out = GenDefaultValue(field, true); + // All FlatBufferBuilder default floating point values are doubles + if (field.value.type.base_type == BASE_TYPE_FLOAT) { + if (out.find("Float") != std::string::npos) { + out.replace(0, 5, "Double"); + } } + // Guarantee all values are doubles + if (out.back() == 'f') out.pop_back(); + return out; + } - - // Generate default values to compare against a default value when - // `force_defaults` is `false`. - // Main differences are: - // - Floats are upcasted to doubles - // - Unsigned are casted to signed - std::string GenFBBDefaultValue(const FieldDef &field) const { - auto out = GenDefaultValue(field, true); - // All FlatBufferBuilder default floating point values are doubles - if (field.value.type.base_type == BASE_TYPE_FLOAT) { - if (out.find("Float") != std::string::npos) { - out.replace(0, 5, "Double"); - } - } - //Guarantee all values are doubles - if (out.back() == 'f') - out.pop_back(); - return out; + // FlatBufferBuilder only store signed types, so this function + // returns a cast for unsigned values + std::string GenFBBValueCast(const FieldDef &field) const { + if (IsUnsigned(field.value.type.base_type)) { + return CastToSigned(field.value.type); } + return ""; + } - - // FlatBufferBuilder only store signed types, so this function - // returns a cast for unsigned values - std::string GenFBBValueCast(const FieldDef &field) const { - if (IsUnsigned(field.value.type.base_type)) { - return CastToSigned(field.value.type); - } - return ""; + std::string GenDefaultValue(const FieldDef &field, + bool force_signed = false) const { + auto &value = field.value; + auto base_type = field.value.type.base_type; + if (IsFloat(base_type)) { + auto val = KotlinFloatGen.GenFloatConstant(field); + if (base_type == BASE_TYPE_DOUBLE && val.back() == 'f') { + val.pop_back(); + } + return val; } - std::string GenDefaultValue(const FieldDef &field, - bool force_signed = false) const { - auto &value = field.value; - auto base_type = field.value.type.base_type; - if (IsFloat(base_type)) { - auto val = KotlinFloatGen.GenFloatConstant(field); - if (base_type == BASE_TYPE_DOUBLE && - val.back() == 'f') { - val.pop_back(); - } - return val; - } - - if (base_type == BASE_TYPE_BOOL) { - return value.constant == "0" ? "false" : "true"; - } + if (base_type == BASE_TYPE_BOOL) { + return value.constant == "0" ? "false" : "true"; + } - std::string suffix = ""; + std::string suffix = ""; - if (base_type == BASE_TYPE_LONG || !force_signed) { - suffix = LiteralSuffix(base_type); - } - return value.constant + suffix; + if (base_type == BASE_TYPE_LONG || !force_signed) { + suffix = LiteralSuffix(base_type); } + return value.constant + suffix; + } - void GenEnum(EnumDef &enum_def, CodeWriter &writer) const { - if (enum_def.generated) return; - - GenerateComment(enum_def.doc_comment, writer, &comment_config); - - writer += "@Suppress(\"unused\")"; - writer += "@ExperimentalUnsignedTypes"; - writer += "class " + Esc(enum_def.name) + " private constructor() {"; - writer.IncrementIdentLevel(); - - GenerateCompanionObject(writer, [&](){ - // Write all properties - auto vals = enum_def.Vals(); - for (auto it = vals.begin(); it != vals.end(); ++it) { - auto &ev = **it; - auto field_type = GenTypeBasic(enum_def.underlying_type.base_type); - auto val = enum_def.ToString(ev); - auto suffix = LiteralSuffix(enum_def.underlying_type.base_type); - writer.SetValue("name", Esc(ev.name)); - writer.SetValue("type", field_type); - writer.SetValue("val", val + suffix); - GenerateComment(ev.doc_comment, writer, &comment_config); - writer += "const val {{name}}: {{type}} = {{val}}"; - } + void GenEnum(EnumDef &enum_def, CodeWriter &writer) const { + if (enum_def.generated) return; + + GenerateComment(enum_def.doc_comment, writer, &comment_config); + + writer += "@Suppress(\"unused\")"; + writer += "@ExperimentalUnsignedTypes"; + writer += "class " + Esc(enum_def.name) + " private constructor() {"; + writer.IncrementIdentLevel(); + + GenerateCompanionObject(writer, [&]() { + // Write all properties + auto vals = enum_def.Vals(); + for (auto it = vals.begin(); it != vals.end(); ++it) { + auto &ev = **it; + auto field_type = GenTypeBasic(enum_def.underlying_type.base_type); + auto val = enum_def.ToString(ev); + auto suffix = LiteralSuffix(enum_def.underlying_type.base_type); + writer.SetValue("name", Esc(ev.name)); + writer.SetValue("type", field_type); + writer.SetValue("val", val + suffix); + GenerateComment(ev.doc_comment, writer, &comment_config); + writer += "const val {{name}}: {{type}} = {{val}}"; + } - // Generate a generate string table for enum values. - // Problem is, if values are very sparse that could generate really - // big tables. Ideally in that case we generate a map lookup - // instead, but for the moment we simply don't output a table at all. - auto range = enum_def.Distance(); - // Average distance between values above which we consider a table - // "too sparse". Change at will. - static const uint64_t kMaxSparseness = 5; - if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) { - GeneratePropertyOneLine(writer, "names", "Array<String>", - [&](){ - writer += "arrayOf(\\"; - auto val = enum_def.Vals().front(); - for (auto it = vals.begin(); it != vals.end(); ++it) { - auto ev = *it; - for (auto k = enum_def.Distance(val, ev); k > 1; --k) - writer += "\"\", \\"; - val = ev; - writer += "\"" + (*it)->name + "\"\\"; - if (it+1 != vals.end()) { - writer += ", \\"; - } - } - writer += ")"; - }); - GenerateFunOneLine(writer, "name", "e: Int", "String", [&](){ - writer += "names[e\\"; - if (enum_def.MinValue()->IsNonZero()) - writer += " - " + enum_def.MinValue()->name + ".toInt()\\"; - writer += "]"; - }); - } + // Generate a generate string table for enum values. + // Problem is, if values are very sparse that could generate really + // big tables. Ideally in that case we generate a map lookup + // instead, but for the moment we simply don't output a table at all. + auto range = enum_def.Distance(); + // Average distance between values above which we consider a table + // "too sparse". Change at will. + static const uint64_t kMaxSparseness = 5; + if (range / static_cast<uint64_t>(enum_def.size()) < kMaxSparseness) { + GeneratePropertyOneLine(writer, "names", "Array<String>", [&]() { + writer += "arrayOf(\\"; + auto val = enum_def.Vals().front(); + for (auto it = vals.begin(); it != vals.end(); ++it) { + auto ev = *it; + for (auto k = enum_def.Distance(val, ev); k > 1; --k) + writer += "\"\", \\"; + val = ev; + writer += "\"" + (*it)->name + "\"\\"; + if (it + 1 != vals.end()) { writer += ", \\"; } + } + writer += ")"; + }); + GenerateFunOneLine(writer, "name", "e: Int", "String", [&]() { + writer += "names[e\\"; + if (enum_def.MinValue()->IsNonZero()) + writer += " - " + enum_def.MinValue()->name + ".toInt()\\"; + writer += "]"; }); - writer.DecrementIdentLevel(); - writer += "}"; + } + }); + writer.DecrementIdentLevel(); + writer += "}"; + } + + // Returns the function name that is able to read a value of the given type. + std::string ByteBufferGetter(const Type &type, + std::string bb_var_name) const { + switch (type.base_type) { + case BASE_TYPE_STRING: return "__string"; + case BASE_TYPE_STRUCT: return "__struct"; + case BASE_TYPE_UNION: return "__union"; + case BASE_TYPE_VECTOR: + return ByteBufferGetter(type.VectorType(), bb_var_name); + case BASE_TYPE_INT: + case BASE_TYPE_UINT: return bb_var_name + ".getInt"; + case BASE_TYPE_SHORT: + case BASE_TYPE_USHORT: return bb_var_name + ".getShort"; + case BASE_TYPE_ULONG: + case BASE_TYPE_LONG: return bb_var_name + ".getLong"; + case BASE_TYPE_FLOAT: return bb_var_name + ".getFloat"; + case BASE_TYPE_DOUBLE: return bb_var_name + ".getDouble"; + case BASE_TYPE_CHAR: + case BASE_TYPE_UCHAR: + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return bb_var_name + ".get"; + case BASE_TYPE_BOOL: return "0.toByte() != " + bb_var_name + ".get"; + default: + return bb_var_name + ".get" + MakeCamel(GenTypeBasic(type.base_type)); } + } - // Returns the function name that is able to read a value of the given type. - std::string ByteBufferGetter(const Type &type, std::string bb_var_name) const { - switch (type.base_type) { - case BASE_TYPE_STRING: - return "__string"; - case BASE_TYPE_STRUCT: - return "__struct"; - case BASE_TYPE_UNION: - return "__union"; - case BASE_TYPE_VECTOR: - return ByteBufferGetter(type.VectorType(), bb_var_name); + std::string ByteBufferSetter(const Type &type) const { + if (IsScalar(type.base_type)) { + switch (type.base_type) { case BASE_TYPE_INT: - case BASE_TYPE_UINT: - return bb_var_name + ".getInt"; + case BASE_TYPE_UINT: return "bb.putInt"; case BASE_TYPE_SHORT: - case BASE_TYPE_USHORT: - return bb_var_name + ".getShort"; + case BASE_TYPE_USHORT: return "bb.putShort"; case BASE_TYPE_ULONG: - case BASE_TYPE_LONG: - return bb_var_name + ".getLong"; - case BASE_TYPE_FLOAT: - return bb_var_name + ".getFloat"; - case BASE_TYPE_DOUBLE: - return bb_var_name + ".getDouble"; + case BASE_TYPE_LONG: return "bb.putLong"; + case BASE_TYPE_FLOAT: return "bb.putFloat"; + case BASE_TYPE_DOUBLE: return "bb.putDouble"; case BASE_TYPE_CHAR: case BASE_TYPE_UCHAR: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return bb_var_name + ".get"; case BASE_TYPE_BOOL: - return "0.toByte() != " + bb_var_name + ".get"; - default: - return bb_var_name + ".get" + MakeCamel(GenTypeBasic(type.base_type)); - } + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return "bb.put"; + default: return "bb.put" + MakeCamel(GenTypeBasic(type.base_type)); + } } + return ""; + } - std::string ByteBufferSetter(const Type &type) const { - if (IsScalar(type.base_type)) { - switch (type.base_type) { - case BASE_TYPE_INT: - case BASE_TYPE_UINT: - return "bb.putInt"; - case BASE_TYPE_SHORT: - case BASE_TYPE_USHORT: - return "bb.putShort"; - case BASE_TYPE_ULONG: - case BASE_TYPE_LONG: - return "bb.putLong"; - case BASE_TYPE_FLOAT: - return "bb.putFloat"; - case BASE_TYPE_DOUBLE: - return "bb.putDouble"; - case BASE_TYPE_CHAR: - case BASE_TYPE_UCHAR: - case BASE_TYPE_BOOL: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return "bb.put"; - default: - return "bb.put" + MakeCamel(GenTypeBasic(type.base_type)); - } - } - return ""; - } + // Returns the function name that is able to read a value of the given type. + std::string GenLookupByKey(flatbuffers::FieldDef *key_field, + const std::string &bb_var_name, + const char *num = nullptr) const { + auto type = key_field->value.type; + return ByteBufferGetter(type, bb_var_name) + "(" + + GenOffsetGetter(key_field, num) + ")"; + } - // Returns the function name that is able to read a value of the given type. - std::string GenLookupByKey(flatbuffers::FieldDef *key_field, - const std::string &bb_var_name, - const char *num = nullptr) const { - auto type = key_field->value.type; - return ByteBufferGetter(type, bb_var_name) + "(" + GenOffsetGetter(key_field, num) + ")"; + // Returns the method name for use with add/put calls. + static std::string GenMethod(const Type &type) { + return IsScalar(type.base_type) ? ToSignedType(type) + : (IsStruct(type) ? "Struct" : "Offset"); + } + // Recursively generate arguments for a constructor, to deal with nested + // structs. + static void GenStructArgs(const StructDef &struct_def, CodeWriter &writer, + const char *nameprefix) { + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure + // names don't clash, and to make it obvious these arguments are + // constructing a nested struct, prefix the name with the field + // name. + GenStructArgs(*field.value.type.struct_def, writer, + (nameprefix + (field.name + "_")).c_str()); + } else { + writer += std::string(", ") + nameprefix + "\\"; + writer += MakeCamel(field.name) + ": \\"; + writer += GenTypeBasic(field.value.type.base_type) + "\\"; + } } + } - // Returns the method name for use with add/put calls. - static std::string GenMethod(const Type &type) { - return IsScalar(type.base_type) ? ToSignedType(type) - : (IsStruct(type) ? "Struct" : "Offset"); + // Recusively generate struct construction statements of the form: + // builder.putType(name); + // and insert manual padding. + static void GenStructBody(const StructDef &struct_def, CodeWriter &writer, + const char *nameprefix) { + writer.SetValue("align", NumToString(struct_def.minalign)); + writer.SetValue("size", NumToString(struct_def.bytesize)); + writer += "builder.prep({{align}}, {{size}})"; + auto fields_vec = struct_def.fields.vec; + for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { + auto &field = **it; + + if (field.padding) { + writer.SetValue("pad", NumToString(field.padding)); + writer += "builder.pad({{pad}})"; + } + if (IsStruct(field.value.type)) { + GenStructBody(*field.value.type.struct_def, writer, + (nameprefix + (field.name + "_")).c_str()); + } else { + writer.SetValue("type", GenMethod(field.value.type)); + writer.SetValue("argname", nameprefix + MakeCamel(field.name, false)); + writer.SetValue("cast", CastToSigned(field.value.type)); + writer += "builder.put{{type}}({{argname}}{{cast}})"; + } } + } - // Recursively generate arguments for a constructor, to deal with nested - // structs. - static void GenStructArgs(const StructDef &struct_def, CodeWriter &writer, - const char *nameprefix) { - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure - // names don't clash, and to make it obvious these arguments are - // constructing a nested struct, prefix the name with the field - // name. - GenStructArgs(*field.value.type.struct_def, writer, - (nameprefix + (field.name + "_")).c_str()); - } else { - writer += std::string(", ") + nameprefix + "\\"; - writer += MakeCamel(field.name) + ": \\"; - writer += GenTypeBasic(field.value.type.base_type) + "\\"; - } - } + std::string GenByteBufferLength(const char *bb_name) const { + std::string bb_len = bb_name; + bb_len += ".capacity()"; + return bb_len; + } + + std::string GenOffsetGetter(flatbuffers::FieldDef *key_field, + const char *num = nullptr) const { + std::string key_offset = + "__offset(" + NumToString(key_field->value.offset) + ", "; + if (num) { + key_offset += num; + key_offset += ", _bb)"; + } else { + key_offset += GenByteBufferLength("bb"); + key_offset += " - tableOffset, bb)"; } + return key_offset; + } - // Recusively generate struct construction statements of the form: - // builder.putType(name); - // and insert manual padding. - static void GenStructBody(const StructDef &struct_def, CodeWriter &writer, - const char *nameprefix) { - writer.SetValue("align", NumToString(struct_def.minalign)); - writer.SetValue("size", NumToString(struct_def.bytesize)); - writer += "builder.prep({{align}}, {{size}})"; - auto fields_vec = struct_def.fields.vec; - for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { - auto &field = **it; + void GenStruct(StructDef &struct_def, CodeWriter &writer) const { + if (struct_def.generated) return; - if (field.padding) { - writer.SetValue("pad", NumToString(field.padding)); - writer += "builder.pad({{pad}})"; - } - if (IsStruct(field.value.type)) { - GenStructBody(*field.value.type.struct_def, writer, - (nameprefix + (field.name + "_")).c_str()); - } else { - writer.SetValue("type", GenMethod(field.value.type)); - writer.SetValue("argname", nameprefix + - MakeCamel(field.name, false)); - writer.SetValue("cast", CastToSigned(field.value.type)); - writer += "builder.put{{type}}({{argname}}{{cast}})"; - } - } - } + GenerateComment(struct_def.doc_comment, writer, &comment_config); + auto fixed = struct_def.fixed; - std::string GenByteBufferLength(const char *bb_name) const { - std::string bb_len = bb_name; - bb_len += ".capacity()"; - return bb_len; - } + writer.SetValue("struct_name", Esc(struct_def.name)); + writer.SetValue("superclass", fixed ? "Struct" : "Table"); - std::string GenOffsetGetter(flatbuffers::FieldDef *key_field, - const char *num = nullptr) const { - std::string key_offset = "__offset(" + - NumToString(key_field->value.offset) + ", "; - if (num) { - key_offset += num; - key_offset += ", _bb)"; - } else { - key_offset += GenByteBufferLength("bb"); - key_offset += " - tableOffset, bb)"; - } - return key_offset; - } + writer += "@Suppress(\"unused\")"; + writer += "@ExperimentalUnsignedTypes"; + writer += "class {{struct_name}} : {{superclass}}() {\n"; - void GenStruct(StructDef &struct_def, CodeWriter &writer) const { - if (struct_def.generated) return; + writer.IncrementIdentLevel(); - GenerateComment(struct_def.doc_comment, writer, &comment_config); - auto fixed = struct_def.fixed; + { + // Generate the __init() method that sets the field in a pre-existing + // accessor object. This is to allow object reuse. + GenerateFun(writer, "__init", "_i: Int, _bb: ByteBuffer", "", + [&]() { writer += "__reset(_i, _bb)"; }); - writer.SetValue("struct_name", Esc(struct_def.name)); - writer.SetValue("superclass", fixed ? "Struct" : "Table"); + // Generate assign method + GenerateFun(writer, "__assign", "_i: Int, _bb: ByteBuffer", + Esc(struct_def.name), [&]() { + writer += "__init(_i, _bb)"; + writer += "return this"; + }); - writer += "@Suppress(\"unused\")"; - writer += "@ExperimentalUnsignedTypes"; - writer += "class {{struct_name}} : {{superclass}}() {\n"; + // Generate all getters + GenerateStructGetters(struct_def, writer); - writer.IncrementIdentLevel(); + // Generate Static Fields + GenerateCompanionObject(writer, [&]() { + if (!struct_def.fixed) { + FieldDef *key_field = nullptr; - { - // Generate the __init() method that sets the field in a pre-existing - // accessor object. This is to allow object reuse. - GenerateFun(writer, "__init", "_i: Int, _bb: ByteBuffer", "", [&]() { - writer += "__reset(_i, _bb)"; - }); + // Generate verson check method. + // Force compile time error if not using the same version + // runtime. + GenerateFunOneLine(writer, "validateVersion", "", "", [&]() { + writer += "Constants.FLATBUFFERS_1_11_1()"; + }); - // Generate assign method - GenerateFun(writer, "__assign", "_i: Int, _bb: ByteBuffer", - Esc(struct_def.name), [&]() { - writer += "__init(_i, _bb)"; - writer += "return this"; - }); + GenerateGetRootAsAccessors(Esc(struct_def.name), writer); + GenerateBufferHasIdentifier(struct_def, writer); + GenerateTableCreator(struct_def, writer); - // Generate all getters - GenerateStructGetters(struct_def, writer); + GenerateStartStructMethod(struct_def, writer); - // Generate Static Fields - GenerateCompanionObject(writer, [&](){ + // Static Add for fields + auto fields = struct_def.fields.vec; + int field_pos = -1; + for (auto it = fields.begin(); it != fields.end(); ++it) { + auto &field = **it; + field_pos++; + if (field.deprecated) continue; + if (field.key) key_field = &field; + GenerateAddField(NumToString(field_pos), field, writer); + + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + auto vector_type = field.value.type.VectorType(); + if (!IsStruct(vector_type)) { + GenerateCreateVectorField(field, writer); + } + GenerateStartVectorField(field, writer); + } + } + + GenerateEndStructMethod(struct_def, writer); + auto file_identifier = parser_.file_identifier_; + if (parser_.root_struct_def_ == &struct_def) { + GenerateFinishStructBuffer(struct_def, file_identifier, writer); + GenerateFinishSizePrefixed(struct_def, file_identifier, writer); + } + + if (struct_def.has_key) { + GenerateLookupByKey(key_field, struct_def, writer); + } + } else { + GenerateStaticConstructor(struct_def, writer); + } + }); + } - if (!struct_def.fixed) { - FieldDef *key_field = nullptr; + // class closing + writer.DecrementIdentLevel(); + writer += "}"; + } - // Generate verson check method. - // Force compile time error if not using the same version - // runtime. - GenerateFunOneLine(writer, "validateVersion", "", "", [&](){ - writer += "Constants.FLATBUFFERS_1_11_1()"; - }); + // TODO: move key_field to reference instead of pointer + void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def, + CodeWriter &writer) const { + std::stringstream params; + params << "obj: " << Esc(struct_def.name) << "?" + << ", "; + params << "vectorLocation: Int, "; + params << "key: " << GenTypeGet(key_field->value.type) << ", "; + params << "bb: ByteBuffer"; + + auto statements = [&]() { + auto base_type = key_field->value.type.base_type; + writer.SetValue("struct_name", Esc(struct_def.name)); + if (base_type == BASE_TYPE_STRING) { + writer += + "val byteKey = key." + "toByteArray(Table.UTF8_CHARSET.get()!!)"; + } + writer += "var span = bb.getInt(vectorLocation - 4)"; + writer += "var start = 0"; + writer += "while (span != 0) {"; + writer.IncrementIdentLevel(); + writer += "var middle = span / 2"; + writer += + "val tableOffset = __indirect(vector" + "Location + 4 * (start + middle), bb)"; + if (key_field->value.type.base_type == BASE_TYPE_STRING) { + writer += "val comp = compareStrings(\\"; + writer += GenOffsetGetter(key_field) + "\\"; + writer += ", byteKey, bb)"; + } else { + auto cast = CastToUsigned(key_field->value.type); + auto get_val = GenLookupByKey(key_field, "bb"); + writer += "val value = " + get_val + cast; + writer += "val comp = value.compareTo(key)"; + } + writer += "when {"; + writer.IncrementIdentLevel(); + writer += "comp > 0 -> span = middle"; + writer += "comp < 0 -> {"; + writer.IncrementIdentLevel(); + writer += "middle++"; + writer += "start += middle"; + writer += "span -= middle"; + writer.DecrementIdentLevel(); + writer += "}"; // end comp < 0 + writer += "else -> {"; + writer.IncrementIdentLevel(); + writer += "return (obj ?: {{struct_name}}()).__assign(tableOffset, bb)"; + writer.DecrementIdentLevel(); + writer += "}"; // end else + writer.DecrementIdentLevel(); + writer += "}"; // end when + writer.DecrementIdentLevel(); + writer += "}"; // end while + writer += "return null"; + }; + GenerateFun(writer, "__lookup_by_key", params.str(), + Esc(struct_def.name) + "?", statements); + } - GenerateGetRootAsAccessors(Esc(struct_def.name), writer); - GenerateBufferHasIdentifier(struct_def, writer); - GenerateTableCreator(struct_def, writer); - - GenerateStartStructMethod(struct_def, writer); - - // Static Add for fields - auto fields = struct_def.fields.vec; - int field_pos = -1; - for (auto it = fields.begin(); it != fields.end(); ++it) { - auto &field = **it; - field_pos++; - if (field.deprecated) continue; - if (field.key) key_field = &field; - GenerateAddField(NumToString(field_pos), field, writer); - - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - auto vector_type = field.value.type.VectorType(); - if (!IsStruct(vector_type)) { - GenerateCreateVectorField(field, writer); - } - GenerateStartVectorField(field, writer); - } - } - - GenerateEndStructMethod(struct_def, writer); - auto file_identifier = parser_.file_identifier_; - if (parser_.root_struct_def_ == &struct_def) { - GenerateFinishStructBuffer(struct_def, - file_identifier, - writer); - GenerateFinishSizePrefixed(struct_def, - file_identifier, - writer); - } - - if (struct_def.has_key) { - GenerateLookupByKey(key_field, struct_def, writer); - } - } else { - GenerateStaticConstructor(struct_def, writer); - } - }); - } + void GenerateFinishSizePrefixed(StructDef &struct_def, + const std::string &identifier, + CodeWriter &writer) const { + auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; + auto params = "builder: FlatBufferBuilder, offset: Int"; + auto method_name = "finishSizePrefixed" + Esc(struct_def.name) + "Buffer"; + GenerateFunOneLine(writer, method_name, params, "", [&]() { + writer += "builder.finishSizePrefixed(offset" + id + ")"; + }); + } + void GenerateFinishStructBuffer(StructDef &struct_def, + const std::string &identifier, + CodeWriter &writer) const { + auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; + auto params = "builder: FlatBufferBuilder, offset: Int"; + auto method_name = "finish" + Esc(struct_def.name) + "Buffer"; + GenerateFunOneLine(writer, method_name, params, "", + [&]() { writer += "builder.finish(offset" + id + ")"; }); + } - // class closing - writer.DecrementIdentLevel(); - writer += "}"; - } + void GenerateEndStructMethod(StructDef &struct_def, + CodeWriter &writer) const { + // Generate end{{TableName}}(builder: FlatBufferBuilder) method + auto name = "end" + Esc(struct_def.name); + auto params = "builder: FlatBufferBuilder"; + auto returns = "Int"; + auto field_vec = struct_def.fields.vec; + + GenerateFun(writer, name, params, returns, [&]() { + writer += "val o = builder.endTable()"; + writer.IncrementIdentLevel(); + for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated || !field.required) { continue; } + writer.SetValue("offset", NumToString(field.value.offset)); + writer += "builder.required(o, {{offset}})"; + } + writer.DecrementIdentLevel(); + writer += "return o"; + }); + } - // TODO: move key_field to reference instead of pointer - void GenerateLookupByKey(FieldDef *key_field, StructDef &struct_def, - CodeWriter &writer) const { - std::stringstream params; - params << "obj: " << Esc(struct_def.name) << "?" << ", "; - params << "vectorLocation: Int, "; - params << "key: " << GenTypeGet(key_field->value.type) << ", "; - params << "bb: ByteBuffer"; - - auto statements = [&]() { - auto base_type = key_field->value.type.base_type; - writer.SetValue("struct_name", Esc(struct_def.name)); - if (base_type == BASE_TYPE_STRING) { - writer += "val byteKey = key." - "toByteArray(Table.UTF8_CHARSET.get()!!)"; - } - writer += "var span = bb.getInt(vectorLocation - 4)"; - writer += "var start = 0"; - writer += "while (span != 0) {"; - writer.IncrementIdentLevel(); - writer += "var middle = span / 2"; - writer += "val tableOffset = __indirect(vector" - "Location + 4 * (start + middle), bb)"; - if (key_field->value.type.base_type == BASE_TYPE_STRING) { - writer += "val comp = compareStrings(\\"; - writer += GenOffsetGetter(key_field) + "\\"; - writer += ", byteKey, bb)"; - } else { - auto cast = CastToUsigned(key_field->value.type); - auto get_val = GenLookupByKey(key_field, "bb"); - writer += "val value = " + get_val + cast; - writer += "val comp = value.compareTo(key)"; - } - writer += "when {"; - writer.IncrementIdentLevel(); - writer += "comp > 0 -> span = middle"; - writer += "comp < 0 -> {"; - writer.IncrementIdentLevel(); - writer += "middle++"; - writer += "start += middle"; - writer += "span -= middle"; - writer.DecrementIdentLevel(); - writer += "}"; // end comp < 0 - writer += "else -> {"; - writer.IncrementIdentLevel(); - writer += "return (obj ?: {{struct_name}}()).__assign(tableOffset, bb)"; - writer.DecrementIdentLevel(); - writer += "}"; // end else - writer.DecrementIdentLevel(); - writer += "}"; // end when - writer.DecrementIdentLevel(); - writer += "}"; // end while - writer += "return null"; - }; - GenerateFun(writer, "__lookup_by_key", - params.str(), - Esc(struct_def.name) + "?", - statements); - } + // Generate a method to create a vector from a Kotlin array. + void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer) const { + auto vector_type = field.value.type.VectorType(); + auto method_name = "create" + MakeCamel(Esc(field.name)) + "Vector"; + auto params = "builder: FlatBufferBuilder, data: " + + GenTypeBasic(vector_type.base_type) + "Array"; + writer.SetValue("size", NumToString(InlineSize(vector_type))); + writer.SetValue("align", NumToString(InlineAlignment(vector_type))); + writer.SetValue("root", GenMethod(vector_type)); + writer.SetValue("cast", CastToSigned(vector_type)); + + GenerateFun(writer, method_name, params, "Int", [&]() { + writer += "builder.startVector({{size}}, data.size, {{align}})"; + writer += "for (i in data.size - 1 downTo 0) {"; + writer.IncrementIdentLevel(); + writer += "builder.add{{root}}(data[i]{{cast}})"; + writer.DecrementIdentLevel(); + writer += "}"; + writer += "return builder.endVector()"; + }); + } - void GenerateFinishSizePrefixed(StructDef &struct_def, - const std::string &identifier, - CodeWriter &writer) const { - auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; - auto params = "builder: FlatBufferBuilder, offset: Int"; - auto method_name = "finishSizePrefixed" + Esc(struct_def.name) + "Buffer"; - GenerateFunOneLine(writer, method_name, params, "", [&]() { - writer += "builder.finishSizePrefixed(offset" + id + ")"; - }); - } - void GenerateFinishStructBuffer(StructDef &struct_def, - const std::string &identifier, - CodeWriter &writer) const { - auto id = identifier.length() > 0 ? ", \"" + identifier + "\"" : ""; - auto params = "builder: FlatBufferBuilder, offset: Int"; - auto method_name = "finish" + Esc(struct_def.name) + "Buffer"; - GenerateFunOneLine(writer, method_name, params, "", [&]() { - writer += "builder.finish(offset" + id + ")"; + void GenerateStartVectorField(FieldDef &field, CodeWriter &writer) const { + // Generate a method to start a vector, data to be added manually + // after. + auto vector_type = field.value.type.VectorType(); + auto params = "builder: FlatBufferBuilder, numElems: Int"; + writer.SetValue("size", NumToString(InlineSize(vector_type))); + writer.SetValue("align", NumToString(InlineAlignment(vector_type))); + + GenerateFunOneLine( + writer, "start" + MakeCamel(Esc(field.name) + "Vector", true), params, + "", [&]() { + writer += "builder.startVector({{size}}, numElems, {{align}})"; }); - } + } - void GenerateEndStructMethod(StructDef &struct_def, CodeWriter &writer) const { - // Generate end{{TableName}}(builder: FlatBufferBuilder) method - auto name = "end" + Esc(struct_def.name); - auto params = "builder: FlatBufferBuilder"; - auto returns = "Int"; - auto field_vec = struct_def.fields.vec; - - GenerateFun(writer, name, params, returns, [&](){ - writer += "val o = builder.endTable()"; - writer.IncrementIdentLevel(); - for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated || !field.required) { - continue; - } - writer.SetValue("offset", NumToString(field.value.offset)); - writer += "builder.required(o, {{offset}})"; - } - writer.DecrementIdentLevel(); - writer += "return o"; - }); - } + void GenerateAddField(std::string field_pos, FieldDef &field, + CodeWriter &writer) const { + auto field_type = GenTypeBasic(field.value.type.base_type); + auto secondArg = MakeCamel(Esc(field.name), false) + ": " + field_type; + GenerateFunOneLine(writer, "add" + MakeCamel(Esc(field.name), true), + "builder: FlatBufferBuilder, " + secondArg, "", [&]() { + auto method = GenMethod(field.value.type); + writer.SetValue("field_name", + MakeCamel(Esc(field.name), false)); + writer.SetValue("method_name", method); + writer.SetValue("pos", field_pos); + writer.SetValue("default", GenFBBDefaultValue(field)); + writer.SetValue("cast", GenFBBValueCast(field)); + + writer += "builder.add{{method_name}}({{pos}}, \\"; + writer += "{{field_name}}{{cast}}, {{default}})"; + }); + } - // Generate a method to create a vector from a Kotlin array. - void GenerateCreateVectorField(FieldDef &field, CodeWriter &writer) const { - auto vector_type = field.value.type.VectorType(); - auto method_name = "create" + MakeCamel(Esc(field.name)) + "Vector"; - auto params = "builder: FlatBufferBuilder, data: " + - GenTypeBasic(vector_type.base_type) + "Array"; - writer.SetValue("size", NumToString(InlineSize(vector_type))); - writer.SetValue("align", NumToString(InlineAlignment(vector_type))); - writer.SetValue("root", GenMethod(vector_type)); - writer.SetValue("cast", CastToSigned(vector_type)); - - GenerateFun(writer, method_name, params, "Int", [&](){ - writer += "builder.startVector({{size}}, data.size, {{align}})"; - writer += "for (i in data.size - 1 downTo 0) {"; - writer.IncrementIdentLevel(); - writer += "builder.add{{root}}(data[i]{{cast}})"; - writer.DecrementIdentLevel(); - writer += "}"; - writer += "return builder.endVector()"; - }); + static std::string ToSignedType(const Type &type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return GenTypeBasic(BASE_TYPE_INT); + case BASE_TYPE_ULONG: return GenTypeBasic(BASE_TYPE_LONG); + case BASE_TYPE_UCHAR: + case BASE_TYPE_NONE: + case BASE_TYPE_UTYPE: return GenTypeBasic(BASE_TYPE_CHAR); + case BASE_TYPE_USHORT: return GenTypeBasic(BASE_TYPE_SHORT); + case BASE_TYPE_VECTOR: return ToSignedType(type.VectorType()); + default: return GenTypeBasic(type.base_type); } + } - void GenerateStartVectorField(FieldDef &field, CodeWriter &writer) const { - // Generate a method to start a vector, data to be added manually - // after. - auto vector_type = field.value.type.VectorType(); - auto params = "builder: FlatBufferBuilder, numElems: Int"; - writer.SetValue("size", NumToString(InlineSize(vector_type))); - writer.SetValue("align", NumToString(InlineAlignment(vector_type))); - - GenerateFunOneLine(writer, - "start" + MakeCamel(Esc(field.name) + "Vector", true), - params, - "", - [&]() { - writer += "builder.startVector({{size}}, numElems, {{align}})"; - }); - } + static std::string FlexBufferBuilderCast(const std::string &method, + FieldDef &field, bool isFirst) { + auto field_type = GenTypeBasic(field.value.type.base_type); + std::string to_type; + if (method == "Boolean") + to_type = "Boolean"; + else if (method == "Long") + to_type = "Long"; + else if (method == "Int" || method == "Offset" || method == "Struct") + to_type = "Int"; + else if (method == "Byte" || method.empty()) + to_type = isFirst ? "Byte" : "Int"; + else if (method == "Short") + to_type = isFirst ? "Short" : "Int"; + else if (method == "Double") + to_type = "Double"; + else if (method == "Float") + to_type = isFirst ? "Float" : "Double"; + else if (method == "UByte") + + if (field_type != to_type) return ".to" + to_type + "()"; + return ""; + } - void GenerateAddField(std::string field_pos, FieldDef &field, - CodeWriter &writer) const { - auto field_type = GenTypeBasic(field.value.type.base_type); - auto secondArg = MakeCamel(Esc(field.name), false) + ": " + field_type; - GenerateFunOneLine(writer, "add" + MakeCamel(Esc(field.name), true), - "builder: FlatBufferBuilder, " + secondArg, "", [&](){ - auto method = GenMethod(field.value.type); - writer.SetValue("field_name", MakeCamel(Esc(field.name), false)); - writer.SetValue("method_name", method); - writer.SetValue("pos", field_pos); - writer.SetValue("default", GenFBBDefaultValue(field)); - writer.SetValue("cast", GenFBBValueCast(field)); - - writer += "builder.add{{method_name}}({{pos}}, \\"; - writer += "{{field_name}}{{cast}}, {{default}})"; - }); - } + // fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11) + void GenerateStartStructMethod(StructDef &struct_def, + CodeWriter &code) const { + GenerateFunOneLine(code, "start" + Esc(struct_def.name), + "builder: FlatBufferBuilder", "", [&]() { + code += "builder.startTable(" + + NumToString(struct_def.fields.vec.size()) + + ")"; + }); + } - static std::string ToSignedType(const Type & type) { - switch(type.base_type) { - case BASE_TYPE_UINT: - return GenTypeBasic(BASE_TYPE_INT); - case BASE_TYPE_ULONG: - return GenTypeBasic(BASE_TYPE_LONG); - case BASE_TYPE_UCHAR: - case BASE_TYPE_NONE: - case BASE_TYPE_UTYPE: - return GenTypeBasic(BASE_TYPE_CHAR); - case BASE_TYPE_USHORT: - return GenTypeBasic(BASE_TYPE_SHORT); - case BASE_TYPE_VECTOR: - return ToSignedType(type.VectorType()); - default: - return GenTypeBasic(type.base_type); - } + void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer) const { + // Generate a method that creates a table in one go. This is only possible + // when the table has no struct fields, since those have to be created + // inline, and there's no way to do so in Java. + bool has_no_struct_fields = true; + int num_fields = 0; + auto fields_vec = struct_def.fields.vec; + + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + if (IsStruct(field.value.type)) { + has_no_struct_fields = false; + } else { + num_fields++; + } } + // JVM specifications restrict default constructor params to be < 255. + // Longs and doubles take up 2 units, so we set the limit to be < 127. + if (has_no_struct_fields && num_fields && num_fields < 127) { + // Generate a table constructor of the form: + // public static int createName(FlatBufferBuilder builder, args...) + + auto name = "create" + Esc(struct_def.name); + std::stringstream params; + params << "builder: FlatBufferBuilder"; + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + params << ", " << MakeCamel(Esc(field.name), false); + if (!IsScalar(field.value.type.base_type)) { + params << "Offset: "; + } else { + params << ": "; + } + params << GenTypeBasic(field.value.type.base_type); + } - static std::string FlexBufferBuilderCast(const std::string &method, - FieldDef &field, - bool isFirst) { - auto field_type = GenTypeBasic(field.value.type.base_type); - std::string to_type; - if (method == "Boolean") - to_type = "Boolean"; - else if (method == "Long") - to_type = "Long"; - else if (method == "Int" || method == "Offset" || method == "Struct") - to_type = "Int"; - else if (method == "Byte" || method.empty()) - to_type = isFirst ? "Byte" : "Int"; - else if (method == "Short") - to_type = isFirst ? "Short" : "Int"; - else if (method == "Double") - to_type = "Double"; - else if (method == "Float") - to_type = isFirst ? "Float" : "Double"; - else if (method == "UByte") - - if (field_type != to_type) - return ".to" + to_type + "()"; - return ""; - } + GenerateFun(writer, name, params.str(), "Int", [&]() { + writer.SetValue("vec_size", NumToString(fields_vec.size())); - // fun startMonster(builder: FlatBufferBuilder) = builder.startTable(11) - void GenerateStartStructMethod(StructDef &struct_def, CodeWriter &code) const { - GenerateFunOneLine(code, "start" + Esc(struct_def.name), - "builder: FlatBufferBuilder", "", [&] () { - code += "builder.startTable("+ NumToString(struct_def.fields.vec.size()) + ")"; - }); + writer += "builder.startTable({{vec_size}})"; + + auto sortbysize = struct_def.sortbysize; + auto largest = sortbysize ? sizeof(largest_scalar_t) : 1; + for (size_t size = largest; size; size /= 2) { + for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); ++it) { + auto &field = **it; + auto base_type_size = SizeOf(field.value.type.base_type); + if (!field.deprecated && (!sortbysize || size == base_type_size)) { + writer.SetValue("camel_field_name", + MakeCamel(Esc(field.name), true)); + writer.SetValue("field_name", MakeCamel(Esc(field.name), false)); + + writer += "add{{camel_field_name}}(builder, {{field_name}}\\"; + if (!IsScalar(field.value.type.base_type)) { + writer += "Offset\\"; + } + writer += ")"; + } + } + } + writer += "return end{{struct_name}}(builder)"; + }); } + } + void GenerateBufferHasIdentifier(StructDef &struct_def, + CodeWriter &writer) const { + auto file_identifier = parser_.file_identifier_; + // Check if a buffer has the identifier. + if (parser_.root_struct_def_ != &struct_def || !file_identifier.length()) + return; + auto name = MakeCamel(Esc(struct_def.name), false); + GenerateFunOneLine(writer, name + "BufferHasIdentifier", "_bb: ByteBuffer", + "Boolean", [&]() { + writer += "__has_identifier(_bb, \"" + + file_identifier + "\")"; + }); + } - void GenerateTableCreator(StructDef &struct_def, CodeWriter &writer) const { - // Generate a method that creates a table in one go. This is only possible - // when the table has no struct fields, since those have to be created - // inline, and there's no way to do so in Java. - bool has_no_struct_fields = true; - int num_fields = 0; - auto fields_vec = struct_def.fields.vec; + void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const { + auto fields_vec = struct_def.fields.vec; + FieldDef *key_field = nullptr; + for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; + if (field.key) key_field = &field; + + GenerateComment(field.doc_comment, writer, &comment_config); + + auto field_name = MakeCamel(Esc(field.name), false); + auto field_type = GenTypeGet(field.value.type); + auto field_default_value = GenDefaultValue(field); + auto return_type = GenTypeGet(field.value.type); + auto bbgetter = ByteBufferGetter(field.value.type, "bb"); + auto ucast = CastToUsigned(field); + auto offset_val = NumToString(field.value.offset); + auto offset_prefix = + "val o = __offset(" + offset_val + "); return o != 0 ? "; + auto value_base_type = field.value.type.base_type; + // Most field accessors need to retrieve and test the field offset + // first, this is the offset value for that: + writer.SetValue("offset", NumToString(field.value.offset)); + writer.SetValue("return_type", return_type); + writer.SetValue("field_type", field_type); + writer.SetValue("field_name", field_name); + writer.SetValue("field_default", field_default_value); + writer.SetValue("bbgetter", bbgetter); + writer.SetValue("ucast", ucast); + + auto opt_ret_type = return_type + "?"; + // Generate the accessors that don't do object reuse. + if (value_base_type == BASE_TYPE_STRUCT) { + // Calls the accessor that takes an accessor object with a + // new object. + // val pos + // get() = pos(Vec3()) + GenerateGetterOneLine(writer, field_name, opt_ret_type, [&]() { + writer += "{{field_name}}({{field_type}}())"; + }); + } else if (value_base_type == BASE_TYPE_VECTOR && + field.value.type.element == BASE_TYPE_STRUCT) { + // Accessors for vectors of structs also take accessor objects, + // this generates a variant without that argument. + // ex: fun weapons(j: Int) = weapons(Weapon(), j) + GenerateFunOneLine(writer, field_name, "j: Int", opt_ret_type, [&]() { + writer += "{{field_name}}({{return_type}}(), j)"; + }); + } - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - if (IsStruct(field.value.type)) { - has_no_struct_fields = false; + if (IsScalar(value_base_type)) { + if (struct_def.fixed) { + GenerateGetterOneLine(writer, field_name, return_type, [&]() { + writer += "{{bbgetter}}(bb_pos + {{offset}}){{ucast}}"; + }); + } else { + GenerateGetter(writer, field_name, return_type, [&]() { + writer += "val o = __offset({{offset}})"; + writer += + "return if(o != 0) {{bbgetter}}" + "(o + bb_pos){{ucast}} else " + "{{field_default}}"; + }); + } + } else { + switch (value_base_type) { + case BASE_TYPE_STRUCT: + if (struct_def.fixed) { + // create getter with object reuse + // ex: + // fun pos(obj: Vec3) : Vec3? = obj.__assign(bb_pos + 4, bb) + // ? adds nullability annotation + GenerateFunOneLine( + writer, field_name, "obj: " + field_type, return_type + "?", + [&]() { writer += "obj.__assign(bb_pos + {{offset}}, bb)"; }); } else { - num_fields++; + // create getter with object reuse + // ex: + // fun pos(obj: Vec3) : Vec3? { + // val o = __offset(4) + // return if(o != 0) { + // obj.__assign(o + bb_pos, bb) + // else { + // null + // } + // } + // ? adds nullability annotation + GenerateFun( + writer, field_name, "obj: " + field_type, return_type + "?", + [&]() { + auto fixed = field.value.type.struct_def->fixed; + + writer.SetValue("seek", Indirect("o + bb_pos", fixed)); + OffsetWrapper( + writer, offset_val, + [&]() { writer += "obj.__assign({{seek}}, bb)"; }, + [&]() { writer += "null"; }); + }); } - } - // JVM specifications restrict default constructor params to be < 255. - // Longs and doubles take up 2 units, so we set the limit to be < 127. - if (has_no_struct_fields && num_fields && num_fields < 127) { - // Generate a table constructor of the form: - // public static int createName(FlatBufferBuilder builder, args...) - - auto name = "create" + Esc(struct_def.name); - std::stringstream params; - params << "builder: FlatBufferBuilder"; - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - params << ", " << MakeCamel(Esc(field.name), false); - if (!IsScalar(field.value.type.base_type)){ - params << "Offset: "; - } else { - params << ": "; - } - params << GenTypeBasic(field.value.type.base_type); + break; + case BASE_TYPE_STRING: + // create string getter + // e.g. + // val Name : String? + // get() = { + // val o = __offset(10) + // return if (o != 0) __string(o + bb_pos) else null + // } + // ? adds nullability annotation + GenerateGetter(writer, field_name, return_type + "?", [&]() { + writer += "val o = __offset({{offset}})"; + writer += "return if (o != 0) __string(o + bb_pos) else null"; + }); + break; + case BASE_TYPE_VECTOR: { + // e.g. + // fun inventory(j: Int) : UByte { + // val o = __offset(14) + // return if (o != 0) { + // bb.get(__vector(o) + j * 1).toUByte() + // } else { + // 0 + // } + // } + + auto vectortype = field.value.type.VectorType(); + std::string params = "j: Int"; + std::string nullable = IsScalar(vectortype.base_type) ? "" : "?"; + + if (vectortype.base_type == BASE_TYPE_STRUCT || + vectortype.base_type == BASE_TYPE_UNION) { + params = "obj: " + field_type + ", j: Int"; } - GenerateFun(writer, name, params.str(), "Int", [&]() { - writer.SetValue("vec_size", NumToString(fields_vec.size())); - - writer += "builder.startTable({{vec_size}})"; - - auto sortbysize = struct_def.sortbysize; - auto largest = sortbysize ? sizeof(largest_scalar_t) : 1; - for (size_t size = largest; size; size /= 2) { - for (auto it = fields_vec.rbegin(); it != fields_vec.rend(); - ++it) { - auto &field = **it; - auto base_type_size = SizeOf(field.value.type.base_type); - if (!field.deprecated && - (!sortbysize || size == base_type_size)) { - writer.SetValue("camel_field_name", - MakeCamel(Esc(field.name), true)); - writer.SetValue("field_name", - MakeCamel(Esc(field.name), false)); - - writer += "add{{camel_field_name}}(builder, {{field_name}}\\"; - if (!IsScalar(field.value.type.base_type)){ - writer += "Offset\\"; - } - writer += ")"; - } - } + auto ret_type = return_type + nullable; + GenerateFun(writer, field_name, params, ret_type, [&]() { + auto inline_size = NumToString(InlineSize(vectortype)); + auto index = "__vector(o) + j * " + inline_size; + auto not_found = NotFoundReturn(field.value.type.element); + auto found = ""; + writer.SetValue("index", index); + switch (vectortype.base_type) { + case BASE_TYPE_STRUCT: { + bool fixed = vectortype.struct_def->fixed; + writer.SetValue("index", Indirect(index, fixed)); + found = "obj.__assign({{index}}, bb)"; + break; } - writer += "return end{{struct_name}}(builder)"; + case BASE_TYPE_UNION: + found = "{{bbgetter}}(obj, {{index}} - bb_pos){{ucast}}"; + break; + default: found = "{{bbgetter}}({{index}}){{ucast}}"; + } + OffsetWrapper( + writer, offset_val, [&]() { writer += found; }, + [&]() { writer += not_found; }); }); + break; + } + case BASE_TYPE_UNION: + GenerateFun(writer, field_name, "obj: " + field_type, + return_type + "?", [&]() { + writer += OffsetWrapperOneLine( + offset_val, bbgetter + "(obj, o + bb_pos)", + "null"); + }); + break; + default: FLATBUFFERS_ASSERT(0); } + } - } - void GenerateBufferHasIdentifier(StructDef &struct_def, - CodeWriter &writer) const { - auto file_identifier = parser_.file_identifier_; - // Check if a buffer has the identifier. - if (parser_.root_struct_def_ != &struct_def || !file_identifier.length()) - return; - auto name = MakeCamel(Esc(struct_def.name), false); - GenerateFunOneLine(writer, name + "BufferHasIdentifier", - "_bb: ByteBuffer", - "Boolean", - [&]() { - writer += "__has_identifier(_bb, \"" + file_identifier + "\")"; + if (value_base_type == BASE_TYPE_VECTOR) { + // Generate Lenght functions for vectors + GenerateGetter(writer, field_name + "Length", "Int", [&]() { + writer += OffsetWrapperOneLine(offset_val, "__vector_len(o)", "0"); }); - } - - void GenerateStructGetters(StructDef &struct_def, CodeWriter &writer) const { - auto fields_vec = struct_def.fields.vec; - FieldDef *key_field = nullptr; - for (auto it = fields_vec.begin(); it != fields_vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; - if (field.key) key_field = &field; - GenerateComment(field.doc_comment, writer, &comment_config); - - auto field_name = MakeCamel(Esc(field.name), false); - auto field_type = GenTypeGet(field.value.type); - auto field_default_value = GenDefaultValue(field); - auto return_type = GenTypeGet(field.value.type); - auto bbgetter = ByteBufferGetter(field.value.type, "bb"); - auto ucast = CastToUsigned(field); - auto offset_val = NumToString(field.value.offset); - auto offset_prefix = "val o = __offset(" + offset_val - + "); return o != 0 ? "; - auto value_base_type = field.value.type.base_type; - // Most field accessors need to retrieve and test the field offset - // first, this is the offset value for that: - writer.SetValue("offset", NumToString(field.value.offset)); - writer.SetValue("return_type", return_type); - writer.SetValue("field_type", field_type); - writer.SetValue("field_name", field_name); - writer.SetValue("field_default", field_default_value); - writer.SetValue("bbgetter", bbgetter); - writer.SetValue("ucast", ucast); - - auto opt_ret_type = return_type + "?"; - // Generate the accessors that don't do object reuse. - if (value_base_type == BASE_TYPE_STRUCT) { - // Calls the accessor that takes an accessor object with a - // new object. - // val pos - // get() = pos(Vec3()) - GenerateGetterOneLine(writer, field_name, opt_ret_type, [&](){ - writer += "{{field_name}}({{field_type}}())"; - }); - } else if (value_base_type == BASE_TYPE_VECTOR && - field.value.type.element == BASE_TYPE_STRUCT) { - // Accessors for vectors of structs also take accessor objects, - // this generates a variant without that argument. - // ex: fun weapons(j: Int) = weapons(Weapon(), j) - GenerateFunOneLine(writer, field_name, "j: Int", opt_ret_type, [&](){ - writer += "{{field_name}}({{return_type}}(), j)"; - }); + // See if we should generate a by-key accessor. + if (field.value.type.element == BASE_TYPE_STRUCT && + !field.value.type.struct_def->fixed) { + auto &sd = *field.value.type.struct_def; + auto &fields = sd.fields.vec; + for (auto kit = fields.begin(); kit != fields.end(); ++kit) { + auto &kfield = **kit; + if (kfield.key) { + auto qualified_name = WrapInNameSpace(sd); + auto name = MakeCamel(Esc(field.name), false) + "ByKey"; + auto params = "key: " + GenTypeGet(kfield.value.type); + auto rtype = qualified_name + "?"; + GenerateFun(writer, name, params, rtype, [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += qualified_name + + ".__lookup_by_key(null, __vector(o), key, bb)"; + }, + [&]() { writer += "null"; }); + }); + + auto param2 = "obj: " + qualified_name + + ", key: " + GenTypeGet(kfield.value.type); + GenerateFun(writer, name, param2, rtype, [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += qualified_name + + ".__lookup_by_key(obj, __vector(o), key, bb)"; + }, + [&]() { writer += "null"; }); + }); + + break; } + } + } + } - if (IsScalar(value_base_type)) { - if (struct_def.fixed) { - GenerateGetterOneLine(writer, field_name, return_type, [&](){ - writer += "{{bbgetter}}(bb_pos + {{offset}}){{ucast}}"; - }); - } else { - GenerateGetter(writer, field_name, return_type, [&](){ - writer += "val o = __offset({{offset}})"; - writer += "return if(o != 0) {{bbgetter}}" - "(o + bb_pos){{ucast}} else " - "{{field_default}}"; - }); - } - } else { - switch (value_base_type) { - case BASE_TYPE_STRUCT: - if (struct_def.fixed) { - // create getter with object reuse - // ex: - // fun pos(obj: Vec3) : Vec3? = obj.__assign(bb_pos + 4, bb) - // ? adds nullability annotation - GenerateFunOneLine(writer, - field_name, "obj: " + field_type , - return_type + "?", [&](){ - writer += "obj.__assign(bb_pos + {{offset}}, bb)"; - }); - } else { - // create getter with object reuse - // ex: - // fun pos(obj: Vec3) : Vec3? { - // val o = __offset(4) - // return if(o != 0) { - // obj.__assign(o + bb_pos, bb) - // else { - // null - // } - // } - // ? adds nullability annotation - GenerateFun(writer, field_name, "obj: " + field_type, - return_type + "?", [&](){ - auto fixed = field.value.type.struct_def->fixed; - - writer.SetValue("seek", Indirect("o + bb_pos", fixed)); - OffsetWrapper(writer, - offset_val, - [&]() { writer += "obj.__assign({{seek}}, bb)"; }, - [&]() { writer += "null"; }); - }); - } - break; - case BASE_TYPE_STRING: - // create string getter - // e.g. - // val Name : String? - // get() = { - // val o = __offset(10) - // return if (o != 0) __string(o + bb_pos) else null - // } - // ? adds nullability annotation - GenerateGetter(writer, field_name, return_type + "?", [&](){ - - writer += "val o = __offset({{offset}})"; - writer += "return if (o != 0) __string(o + bb_pos) else null"; - }); - break; - case BASE_TYPE_VECTOR: { - // e.g. - // fun inventory(j: Int) : UByte { - // val o = __offset(14) - // return if (o != 0) { - // bb.get(__vector(o) + j * 1).toUByte() - // } else { - // 0 - // } - // } - - auto vectortype = field.value.type.VectorType(); - std::string params = "j: Int"; - std::string nullable = IsScalar(vectortype.base_type) ? "" - : "?"; - - if (vectortype.base_type == BASE_TYPE_STRUCT || - vectortype.base_type == BASE_TYPE_UNION) { - params = "obj: " + field_type + ", j: Int"; - } - - auto ret_type = return_type + nullable; - GenerateFun(writer, field_name, params, ret_type, [&](){ - auto inline_size = NumToString(InlineSize(vectortype)); - auto index = "__vector(o) + j * " + inline_size; - auto not_found = NotFoundReturn(field.value.type.element); - auto found = ""; - writer.SetValue("index", index); - switch(vectortype.base_type) { - case BASE_TYPE_STRUCT: { - bool fixed = vectortype.struct_def->fixed; - writer.SetValue("index", Indirect(index, fixed)); - found = "obj.__assign({{index}}, bb)"; - break; - } - case BASE_TYPE_UNION: - found = "{{bbgetter}}(obj, {{index}} - bb_pos){{ucast}}"; - break; - default: - found = "{{bbgetter}}({{index}}){{ucast}}"; - } - OffsetWrapper(writer, offset_val, - [&]() { writer += found; } , - [&]() { writer += not_found; }); - }); - break; - } - case BASE_TYPE_UNION: - GenerateFun(writer, field_name, "obj: " + field_type, - return_type + "?", [&](){ - writer += OffsetWrapperOneLine(offset_val, - bbgetter + "(obj, o + bb_pos)", - "null"); - }); - break; - default: - FLATBUFFERS_ASSERT(0); - } - } + if ((value_base_type == BASE_TYPE_VECTOR && + IsScalar(field.value.type.VectorType().base_type)) || + value_base_type == BASE_TYPE_STRING) { + auto end_idx = + NumToString(value_base_type == BASE_TYPE_STRING + ? 1 + : InlineSize(field.value.type.VectorType())); + // Generate a ByteBuffer accessor for strings & vectors of scalars. + // e.g. + // val inventoryByteBuffer: ByteBuffer + // get = __vector_as_bytebuffer(14, 1) + + GenerateGetterOneLine( + writer, field_name + "AsByteBuffer", "ByteBuffer", [&]() { + writer.SetValue("end", end_idx); + writer += "__vector_as_bytebuffer({{offset}}, {{end}})"; + }); - if (value_base_type == BASE_TYPE_VECTOR) { - // Generate Lenght functions for vectors - GenerateGetter(writer, field_name + "Length", "Int", [&](){ - writer += OffsetWrapperOneLine(offset_val, - "__vector_len(o)", "0"); - }); - - // See if we should generate a by-key accessor. - if (field.value.type.element == BASE_TYPE_STRUCT && - !field.value.type.struct_def->fixed) { - auto &sd = *field.value.type.struct_def; - auto &fields = sd.fields.vec; - for (auto kit = fields.begin(); kit != fields.end(); ++kit) { - auto &kfield = **kit; - if (kfield.key) { - auto qualified_name = WrapInNameSpace(sd); - auto name = MakeCamel(Esc(field.name), false) + "ByKey"; - auto params = "key: " + GenTypeGet(kfield.value.type); - auto rtype = qualified_name + "?"; - GenerateFun(writer, name, params, rtype, [&] () { - OffsetWrapper(writer, offset_val, - [&] () { - writer += qualified_name + - ".__lookup_by_key(null, __vector(o), key, bb)"; - }, - [&] () { - writer += "null"; - }); - }); - - auto param2 = "obj: " + qualified_name + - ", key: " + - GenTypeGet(kfield.value.type); - GenerateFun(writer, name, param2, rtype, [&](){ - OffsetWrapper(writer, offset_val, - [&] () { - writer += qualified_name + - ".__lookup_by_key(obj, __vector(o), key, bb)"; - }, - [&]() { writer += "null"; }); - }); - - break; - } - } - } - } + // Generate a ByteBuffer accessor for strings & vectors of scalars. + // e.g. + // fun inventoryInByteBuffer(_bb: Bytebuffer): + // ByteBuffer = __vector_as_bytebuffer(_bb, 14, 1) + GenerateFunOneLine( + writer, field_name + "InByteBuffer", "_bb: ByteBuffer", + "ByteBuffer", [&]() { + writer.SetValue("end", end_idx); + writer += "__vector_in_bytebuffer(_bb, {{offset}}, {{end}})"; + }); + } - if ((value_base_type == BASE_TYPE_VECTOR && - IsScalar(field.value.type.VectorType().base_type)) || - value_base_type == BASE_TYPE_STRING) { - - auto end_idx = NumToString(value_base_type == BASE_TYPE_STRING - ? 1 - : InlineSize(field.value.type.VectorType())); - // Generate a ByteBuffer accessor for strings & vectors of scalars. - // e.g. - // val inventoryByteBuffer: ByteBuffer - // get = __vector_as_bytebuffer(14, 1) - - GenerateGetterOneLine(writer, field_name + "AsByteBuffer", - "ByteBuffer", [&](){ - writer.SetValue("end", end_idx); - writer += "__vector_as_bytebuffer({{offset}}, {{end}})"; - }); - - // Generate a ByteBuffer accessor for strings & vectors of scalars. - // e.g. - // fun inventoryInByteBuffer(_bb: Bytebuffer): - // ByteBuffer = __vector_as_bytebuffer(_bb, 14, 1) - GenerateFunOneLine(writer, field_name + "InByteBuffer", - "_bb: ByteBuffer", "ByteBuffer", [&](){ - writer.SetValue("end", end_idx); - writer += "__vector_in_bytebuffer(_bb, {{offset}}, {{end}})"; - }); - } + // generate object accessors if is nested_flatbuffer + // fun testnestedflatbufferAsMonster() : Monster? + //{ return testnestedflatbufferAsMonster(new Monster()); } - // generate object accessors if is nested_flatbuffer - //fun testnestedflatbufferAsMonster() : Monster? - //{ return testnestedflatbufferAsMonster(new Monster()); } - - if (field.nested_flatbuffer) { - auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer); - auto nested_method_name = - field_name + "As" + - field.nested_flatbuffer->name; - - GenerateGetterOneLine(writer, - nested_method_name, - nested_type_name + "?", [&](){ - writer += nested_method_name + "(" + nested_type_name + "())"; - }); - - GenerateFun(writer, - nested_method_name, - "obj: " + nested_type_name, - nested_type_name + "?", [&](){ - OffsetWrapper(writer, offset_val, - [&]() { writer += "obj.__assign(__indirect(__vector(o)), bb)"; }, - [&]() { writer += "null";}); - }); - } + if (field.nested_flatbuffer) { + auto nested_type_name = WrapInNameSpace(*field.nested_flatbuffer); + auto nested_method_name = + field_name + "As" + field.nested_flatbuffer->name; - // Generate mutators for scalar fields or vectors of scalars. - if (parser_.opts.mutable_buffer) { - auto value_type = field.value.type; - auto underlying_type = value_base_type == BASE_TYPE_VECTOR - ? value_type.VectorType() - : value_type; - auto name = "mutate" + MakeCamel(Esc(field.name), true); - auto size = NumToString(InlineSize(underlying_type)); - auto params = Esc(field.name) + ": " + GenTypeGet(underlying_type); - // A vector mutator also needs the index of the vector element it should - // mutate. - if (value_base_type == BASE_TYPE_VECTOR) - params.insert(0, "j: Int, "); - - // Boolean parameters have to be explicitly converted to byte - // representation. - auto setter_parameter = underlying_type.base_type == BASE_TYPE_BOOL - ? "(if(" + Esc(field.name) + ") 1 else 0).toByte()" - : Esc(field.name); - - auto setter_index = value_base_type == BASE_TYPE_VECTOR - ? "__vector(o) + j * " + size - : (struct_def.fixed - ? "bb_pos + " + offset_val - : "o + bb_pos"); - if (IsScalar(value_base_type) || (value_base_type == BASE_TYPE_VECTOR && - IsScalar(value_type.VectorType().base_type))) { - - auto statements = [&] () { - writer.SetValue("bbsetter", ByteBufferSetter(underlying_type)); - writer.SetValue("index", setter_index); - writer.SetValue("params", setter_parameter); - writer.SetValue("cast", CastToSigned(field)); - if (struct_def.fixed) { - writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; - } else { - OffsetWrapper(writer, offset_val, [&](){ - writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; - writer += "true"; - }, [&](){ writer += "false";}); - } - }; - - if (struct_def.fixed) { - GenerateFunOneLine(writer, name, params, "ByteBuffer", - statements); - } else { - GenerateFun(writer, name, params, "Boolean", - statements); - } - } - } - } - if (struct_def.has_key && !struct_def.fixed) { - // Key Comparison method - GenerateOverrideFun( - writer, - "keysCompare", - "o1: Int, o2: Int, _bb: ByteBuffer", "Int", [&]() { - if (key_field->value.type.base_type == BASE_TYPE_STRING) { - writer.SetValue("offset", NumToString(key_field->value.offset)); - writer += " return compareStrings(__offset({{offset}}, o1, " - "_bb), __offset({{offset}}, o2, _bb), _bb)"; - - } else { - auto getter1 = GenLookupByKey(key_field, "_bb", "o1"); - auto getter2 = GenLookupByKey(key_field, "_bb", "o2"); - writer += "val val_1 = " + getter1; - writer += "val val_2 = " + getter2; - writer += "return (val_1 - val_2).sign"; - } + GenerateGetterOneLine( + writer, nested_method_name, nested_type_name + "?", [&]() { + writer += nested_method_name + "(" + nested_type_name + "())"; }); - } - } - static std::string CastToUsigned(const FieldDef &field) { - return CastToUsigned(field.value.type); - } - - static std::string CastToUsigned(const Type type) { - switch (type.base_type) { - case BASE_TYPE_UINT: - return ".toUInt()"; - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - return ".toUByte()"; - case BASE_TYPE_USHORT: - return ".toUShort()"; - case BASE_TYPE_ULONG: - return ".toULong()"; - case BASE_TYPE_VECTOR: - return CastToUsigned(type.VectorType()); - default: - return ""; - } - } + GenerateFun(writer, nested_method_name, "obj: " + nested_type_name, + nested_type_name + "?", [&]() { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += + "obj.__assign(__indirect(__vector(o)), bb)"; + }, + [&]() { writer += "null"; }); + }); + } - static std::string CastToSigned(const FieldDef &field) { - return CastToSigned(field.value.type); - } + // Generate mutators for scalar fields or vectors of scalars. + if (parser_.opts.mutable_buffer) { + auto value_type = field.value.type; + auto underlying_type = value_base_type == BASE_TYPE_VECTOR + ? value_type.VectorType() + : value_type; + auto name = "mutate" + MakeCamel(Esc(field.name), true); + auto size = NumToString(InlineSize(underlying_type)); + auto params = Esc(field.name) + ": " + GenTypeGet(underlying_type); + // A vector mutator also needs the index of the vector element it should + // mutate. + if (value_base_type == BASE_TYPE_VECTOR) params.insert(0, "j: Int, "); + + // Boolean parameters have to be explicitly converted to byte + // representation. + auto setter_parameter = + underlying_type.base_type == BASE_TYPE_BOOL + ? "(if(" + Esc(field.name) + ") 1 else 0).toByte()" + : Esc(field.name); + + auto setter_index = + value_base_type == BASE_TYPE_VECTOR + ? "__vector(o) + j * " + size + : (struct_def.fixed ? "bb_pos + " + offset_val : "o + bb_pos"); + if (IsScalar(value_base_type) || + (value_base_type == BASE_TYPE_VECTOR && + IsScalar(value_type.VectorType().base_type))) { + auto statements = [&]() { + writer.SetValue("bbsetter", ByteBufferSetter(underlying_type)); + writer.SetValue("index", setter_index); + writer.SetValue("params", setter_parameter); + writer.SetValue("cast", CastToSigned(field)); + if (struct_def.fixed) { + writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; + } else { + OffsetWrapper( + writer, offset_val, + [&]() { + writer += "{{bbsetter}}({{index}}, {{params}}{{cast}})"; + writer += "true"; + }, + [&]() { writer += "false"; }); + } + }; - static std::string CastToSigned(const Type type) { - switch (type.base_type) { - case BASE_TYPE_UINT: - return ".toInt()"; - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - return ".toByte()"; - case BASE_TYPE_USHORT: - return ".toShort()"; - case BASE_TYPE_ULONG: - return ".toLong()"; - case BASE_TYPE_VECTOR: - return CastToSigned(type.VectorType()); - default: - return ""; + if (struct_def.fixed) { + GenerateFunOneLine(writer, name, params, "ByteBuffer", statements); + } else { + GenerateFun(writer, name, params, "Boolean", statements); + } } + } } + if (struct_def.has_key && !struct_def.fixed) { + // Key Comparison method + GenerateOverrideFun( + writer, "keysCompare", "o1: Int, o2: Int, _bb: ByteBuffer", "Int", + [&]() { + if (key_field->value.type.base_type == BASE_TYPE_STRING) { + writer.SetValue("offset", NumToString(key_field->value.offset)); + writer += + " return compareStrings(__offset({{offset}}, o1, " + "_bb), __offset({{offset}}, o2, _bb), _bb)"; - static std::string LiteralSuffix(const BaseType type) { - switch (type) { - case BASE_TYPE_UINT: - case BASE_TYPE_UCHAR: - case BASE_TYPE_UTYPE: - case BASE_TYPE_USHORT: - return "u"; - case BASE_TYPE_ULONG: - return "UL"; - case BASE_TYPE_LONG: - return "L"; - default: - return ""; - } + } else { + auto getter1 = GenLookupByKey(key_field, "_bb", "o1"); + auto getter2 = GenLookupByKey(key_field, "_bb", "o2"); + writer += "val val_1 = " + getter1; + writer += "val val_2 = " + getter2; + writer += "return (val_1 - val_2).sign"; + } + }); } + } + + static std::string CastToUsigned(const FieldDef &field) { + return CastToUsigned(field.value.type); + } - void GenerateCompanionObject(CodeWriter &code, - const std::function<void()> &callback) const { - code += "companion object {"; - code.IncrementIdentLevel(); - callback(); - code.DecrementIdentLevel(); - code += "}"; + static std::string CastToUsigned(const Type type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return ".toUInt()"; + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: return ".toUByte()"; + case BASE_TYPE_USHORT: return ".toUShort()"; + case BASE_TYPE_ULONG: return ".toULong()"; + case BASE_TYPE_VECTOR: return CastToUsigned(type.VectorType()); + default: return ""; } + } - // Generate a documentation comment, if available. - void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer, - const CommentConfig *config) const { - if (dc.begin() == dc.end()) { - // Don't output empty comment blocks with 0 lines of comment content. - return; - } + static std::string CastToSigned(const FieldDef &field) { + return CastToSigned(field.value.type); + } - if (config != nullptr && config->first_line != nullptr) { - writer += std::string(config->first_line); - } - std::string line_prefix = - ((config != nullptr && config->content_line_prefix != nullptr) - ? config->content_line_prefix - : "///"); - for (auto it = dc.begin(); it != dc.end(); ++it) { - writer += line_prefix + *it; - } - if (config != nullptr && config->last_line != nullptr) { - writer += std::string(config->last_line); - } + static std::string CastToSigned(const Type type) { + switch (type.base_type) { + case BASE_TYPE_UINT: return ".toInt()"; + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: return ".toByte()"; + case BASE_TYPE_USHORT: return ".toShort()"; + case BASE_TYPE_ULONG: return ".toLong()"; + case BASE_TYPE_VECTOR: return CastToSigned(type.VectorType()); + default: return ""; } + } - static void GenerateGetRootAsAccessors(const std::string &struct_name, - CodeWriter &writer) { - // Generate a special accessor for the table that when used as the root - // ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...} - writer.SetValue("gr_name", struct_name); - writer.SetValue("gr_method", "getRootAs" + struct_name); - - // create convenience method that doesn't require an existing object - writer += "fun {{gr_method}}(_bb: ByteBuffer): {{gr_name}} = \\"; - writer += "{{gr_method}}(_bb, {{gr_name}}())"; - - // create method that allows object reuse - // ex: fun Monster getRootAsMonster(_bb: ByteBuffer, obj: Monster) {...} - writer += "fun {{gr_method}}" - "(_bb: ByteBuffer, obj: {{gr_name}}): {{gr_name}} {"; - writer.IncrementIdentLevel(); - writer += "_bb.order(ByteOrder.LITTLE_ENDIAN)"; - writer += "return (obj.__assign(_bb.getInt(_bb.position())" - " + _bb.position(), _bb))"; - writer.DecrementIdentLevel(); - writer += "}"; + static std::string LiteralSuffix(const BaseType type) { + switch (type) { + case BASE_TYPE_UINT: + case BASE_TYPE_UCHAR: + case BASE_TYPE_UTYPE: + case BASE_TYPE_USHORT: return "u"; + case BASE_TYPE_ULONG: return "UL"; + case BASE_TYPE_LONG: return "L"; + default: return ""; } + } - static void GenerateStaticConstructor(const StructDef &struct_def, - CodeWriter &code) { - // create a struct constructor function - auto params = StructConstructorParams(struct_def); - GenerateFun(code, "create" + Esc(struct_def.name), params, "Int", [&](){ - GenStructBody(struct_def, code, ""); - code += "return builder.offset()"; - }); - } + void GenerateCompanionObject(CodeWriter &code, + const std::function<void()> &callback) const { + code += "companion object {"; + code.IncrementIdentLevel(); + callback(); + code.DecrementIdentLevel(); + code += "}"; + } - static std::string StructConstructorParams(const StructDef &struct_def, - const std::string &prefix = "") { - //builder: FlatBufferBuilder - std::stringstream out; - auto field_vec = struct_def.fields.vec; - if (prefix.empty()) { - out << "builder: FlatBufferBuilder"; - } - for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure - // names don't clash, and to make it obvious these arguments are - // constructing a nested struct, prefix the name with the field - // name. - out << StructConstructorParams(*field.value.type.struct_def, - prefix + (Esc(field.name) + "_")); - } else { - out << ", " << prefix << MakeCamel(Esc(field.name), false) - << ": " - << GenTypeBasic(field.value.type.base_type); - } - } - return out.str(); + // Generate a documentation comment, if available. + void GenerateComment(const std::vector<std::string> &dc, CodeWriter &writer, + const CommentConfig *config) const { + if (dc.begin() == dc.end()) { + // Don't output empty comment blocks with 0 lines of comment content. + return; } - static void GeneratePropertyOneLine(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype = x - writer.SetValue("_name", name); - writer.SetValue("_type", type); - writer += "val {{_name}} : {{_type}} = \\"; - body(); + if (config != nullptr && config->first_line != nullptr) { + writer += std::string(config->first_line); } - static void GenerateGetterOneLine(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype get() = x - writer.SetValue("_name", name); - writer.SetValue("_type", type); - writer += "val {{_name}} : {{_type}} get() = \\"; - body(); + std::string line_prefix = + ((config != nullptr && config->content_line_prefix != nullptr) + ? config->content_line_prefix + : "///"); + for (auto it = dc.begin(); it != dc.end(); ++it) { + writer += line_prefix + *it; } - - static void GenerateGetter(CodeWriter &writer, - const std::string &name, - const std::string &type, - const std::function<void()> &body) { - // Generates Kotlin getter for properties - // e.g.: - // val prop: Mytype - // get() = { - // return x - // } - writer.SetValue("name", name); - writer.SetValue("type", type); - writer += "val {{name}} : {{type}}"; - writer.IncrementIdentLevel(); - writer += "get() {"; - writer.IncrementIdentLevel(); - body(); - writer.DecrementIdentLevel(); - writer += "}"; - writer.DecrementIdentLevel(); + if (config != nullptr && config->last_line != nullptr) { + writer += std::string(config->last_line); } + } - static void GenerateFun(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // fun path(j: Int): Vec3 { - // return path(Vec3(), j) - // } - auto noreturn = returnType.empty(); - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type", noreturn ? "" : ": " + returnType); - writer += "fun {{name}}({{params}}) {{return_type}} {"; - writer.IncrementIdentLevel(); - body(); - writer.DecrementIdentLevel(); - writer += "}"; - } + static void GenerateGetRootAsAccessors(const std::string &struct_name, + CodeWriter &writer) { + // Generate a special accessor for the table that when used as the root + // ex: fun getRootAsMonster(_bb: ByteBuffer): Monster {...} + writer.SetValue("gr_name", struct_name); + writer.SetValue("gr_method", "getRootAs" + struct_name); + + // create convenience method that doesn't require an existing object + writer += "fun {{gr_method}}(_bb: ByteBuffer): {{gr_name}} = \\"; + writer += "{{gr_method}}(_bb, {{gr_name}}())"; + + // create method that allows object reuse + // ex: fun Monster getRootAsMonster(_bb: ByteBuffer, obj: Monster) {...} + writer += + "fun {{gr_method}}" + "(_bb: ByteBuffer, obj: {{gr_name}}): {{gr_name}} {"; + writer.IncrementIdentLevel(); + writer += "_bb.order(ByteOrder.LITTLE_ENDIAN)"; + writer += + "return (obj.__assign(_bb.getInt(_bb.position())" + " + _bb.position(), _bb))"; + writer.DecrementIdentLevel(); + writer += "}"; + } - static void GenerateFunOneLine(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // fun path(j: Int): Vec3 = return path(Vec3(), j) - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type_p", returnType.empty() ? "" : - " : " + returnType); - writer += "fun {{name}}({{params}}){{return_type_p}} = \\"; - body(); - } + static void GenerateStaticConstructor(const StructDef &struct_def, + CodeWriter &code) { + // create a struct constructor function + auto params = StructConstructorParams(struct_def); + GenerateFun(code, "create" + Esc(struct_def.name), params, "Int", [&]() { + GenStructBody(struct_def, code, ""); + code += "return builder.offset()"; + }); + } - static void GenerateOverrideFun(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::function<void()> &body) { - // Generates Kotlin function - // e.g.: - // override fun path(j: Int): Vec3 = return path(Vec3(), j) - writer += "override \\"; - GenerateFun(writer, name, params, returnType, body); + static std::string StructConstructorParams(const StructDef &struct_def, + const std::string &prefix = "") { + // builder: FlatBufferBuilder + std::stringstream out; + auto field_vec = struct_def.fields.vec; + if (prefix.empty()) { out << "builder: FlatBufferBuilder"; } + for (auto it = field_vec.begin(); it != field_vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure + // names don't clash, and to make it obvious these arguments are + // constructing a nested struct, prefix the name with the field + // name. + out << StructConstructorParams(*field.value.type.struct_def, + prefix + (Esc(field.name) + "_")); + } else { + out << ", " << prefix << MakeCamel(Esc(field.name), false) << ": " + << GenTypeBasic(field.value.type.base_type); + } } + return out.str(); + } - static void GenerateOverrideFunOneLine(CodeWriter &writer, - const std::string &name, - const std::string ¶ms, - const std::string &returnType, - const std::string &statement) { - // Generates Kotlin function - // e.g.: - // override fun path(j: Int): Vec3 = return path(Vec3(), j) - writer.SetValue("name", name); - writer.SetValue("params", params); - writer.SetValue("return_type", returnType.empty() ? "" : - " : " + returnType); - writer += "override fun {{name}}({{params}}){{return_type}} = \\"; - writer += statement; - } + static void GeneratePropertyOneLine(CodeWriter &writer, + const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype = x + writer.SetValue("_name", name); + writer.SetValue("_type", type); + writer += "val {{_name}} : {{_type}} = \\"; + body(); + } + static void GenerateGetterOneLine(CodeWriter &writer, const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype get() = x + writer.SetValue("_name", name); + writer.SetValue("_type", type); + writer += "val {{_name}} : {{_type}} get() = \\"; + body(); + } - static std::string OffsetWrapperOneLine(const std::string &offset, - const std::string &found, - const std::string ¬_found) { - return "val o = __offset(" + offset + "); return if (o != 0) " + found + - " else " + not_found; - } + static void GenerateGetter(CodeWriter &writer, const std::string &name, + const std::string &type, + const std::function<void()> &body) { + // Generates Kotlin getter for properties + // e.g.: + // val prop: Mytype + // get() = { + // return x + // } + writer.SetValue("name", name); + writer.SetValue("type", type); + writer += "val {{name}} : {{type}}"; + writer.IncrementIdentLevel(); + writer += "get() {"; + writer.IncrementIdentLevel(); + body(); + writer.DecrementIdentLevel(); + writer += "}"; + writer.DecrementIdentLevel(); + } - static void OffsetWrapper(CodeWriter &code, - const std::string &offset, - const std::function<void()> &found, - const std::function<void()> ¬_found) { - code += "val o = __offset(" + offset + ")"; - code +="return if (o != 0) {"; - code.IncrementIdentLevel(); - found(); - code.DecrementIdentLevel(); - code += "} else {"; - code.IncrementIdentLevel(); - not_found(); - code.DecrementIdentLevel(); - code += "}"; - } + static void GenerateFun(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // fun path(j: Int): Vec3 { + // return path(Vec3(), j) + // } + auto noreturn = returnType.empty(); + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type", noreturn ? "" : ": " + returnType); + writer += "fun {{name}}({{params}}) {{return_type}} {"; + writer.IncrementIdentLevel(); + body(); + writer.DecrementIdentLevel(); + writer += "}"; + } - static std::string Indirect(const std::string &index, bool fixed) { - // We apply __indirect() and struct is not fixed. - if (!fixed) - return "__indirect(" + index + ")"; - return index; - } + static void GenerateFunOneLine(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // fun path(j: Int): Vec3 = return path(Vec3(), j) + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type_p", + returnType.empty() ? "" : " : " + returnType); + writer += "fun {{name}}({{params}}){{return_type_p}} = \\"; + body(); + } - static std::string NotFoundReturn(BaseType el) { - switch (el) { - case BASE_TYPE_FLOAT: - return "0.0f"; - case BASE_TYPE_DOUBLE: - return "0.0"; - case BASE_TYPE_BOOL: - return "false"; - case BASE_TYPE_LONG: - case BASE_TYPE_INT: - case BASE_TYPE_CHAR: - case BASE_TYPE_SHORT: - return "0"; - case BASE_TYPE_UINT: - case BASE_TYPE_UCHAR: - case BASE_TYPE_USHORT: - case BASE_TYPE_UTYPE: - return "0u"; - case BASE_TYPE_ULONG: - return "0uL"; - default: - return "null"; - } + static void GenerateOverrideFun(CodeWriter &writer, const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::function<void()> &body) { + // Generates Kotlin function + // e.g.: + // override fun path(j: Int): Vec3 = return path(Vec3(), j) + writer += "override \\"; + GenerateFun(writer, name, params, returnType, body); + } + + static void GenerateOverrideFunOneLine(CodeWriter &writer, + const std::string &name, + const std::string ¶ms, + const std::string &returnType, + const std::string &statement) { + // Generates Kotlin function + // e.g.: + // override fun path(j: Int): Vec3 = return path(Vec3(), j) + writer.SetValue("name", name); + writer.SetValue("params", params); + writer.SetValue("return_type", + returnType.empty() ? "" : " : " + returnType); + writer += "override fun {{name}}({{params}}){{return_type}} = \\"; + writer += statement; + } + + static std::string OffsetWrapperOneLine(const std::string &offset, + const std::string &found, + const std::string ¬_found) { + return "val o = __offset(" + offset + "); return if (o != 0) " + found + + " else " + not_found; + } + + static void OffsetWrapper(CodeWriter &code, const std::string &offset, + const std::function<void()> &found, + const std::function<void()> ¬_found) { + code += "val o = __offset(" + offset + ")"; + code += "return if (o != 0) {"; + code.IncrementIdentLevel(); + found(); + code.DecrementIdentLevel(); + code += "} else {"; + code.IncrementIdentLevel(); + not_found(); + code.DecrementIdentLevel(); + code += "}"; + } + + static std::string Indirect(const std::string &index, bool fixed) { + // We apply __indirect() and struct is not fixed. + if (!fixed) return "__indirect(" + index + ")"; + return index; + } + + static std::string NotFoundReturn(BaseType el) { + switch (el) { + case BASE_TYPE_FLOAT: return "0.0f"; + case BASE_TYPE_DOUBLE: return "0.0"; + case BASE_TYPE_BOOL: return "false"; + case BASE_TYPE_LONG: + case BASE_TYPE_INT: + case BASE_TYPE_CHAR: + case BASE_TYPE_SHORT: return "0"; + case BASE_TYPE_UINT: + case BASE_TYPE_UCHAR: + case BASE_TYPE_USHORT: + case BASE_TYPE_UTYPE: return "0u"; + case BASE_TYPE_ULONG: return "0uL"; + default: return "null"; } + } - // This tracks the current namespace used to determine if a type need to be - // prefixed by its namespace - const Namespace *cur_name_space_; + // This tracks the current namespace used to determine if a type need to be + // prefixed by its namespace + const Namespace *cur_name_space_; }; } // namespace kotlin bool GenerateKotlin(const Parser &parser, const std::string &path, const std::string &file_name) { - kotlin::KotlinGenerator generator(parser, path, file_name); - return generator.generate(); + kotlin::KotlinGenerator generator(parser, path, file_name); + return generator.generate(); } } // namespace flatbuffers diff --git a/src/idl_gen_lobster.cpp b/src/idl_gen_lobster.cpp index ef9e474c..d5c99f7e 100644 --- a/src/idl_gen_lobster.cpp +++ b/src/idl_gen_lobster.cpp @@ -27,14 +27,16 @@ namespace lobster { class LobsterGenerator : public BaseGenerator { public: - LobsterGenerator(const Parser &parser, const std::string &path, - const std::string &file_name) + LobsterGenerator(const Parser &parser, const std::string &path, + const std::string &file_name) : BaseGenerator(parser, path, file_name, "" /* not used */, "_") { - static const char * const keywords[] = { - "nil", "true", "false", "return", "struct", "class", "import", "int", - "float", "string", "any", "def", "is", "from", "program", "private", - "coroutine", "resource", "enum", "typeof", "var", "let", "pakfile", - "switch", "case", "default", "namespace", "not", "and", "or", "bool", + static const char *const keywords[] = { + "nil", "true", "false", "return", "struct", "class", + "import", "int", "float", "string", "any", "def", + "is", "from", "program", "private", "coroutine", "resource", + "enum", "typeof", "var", "let", "pakfile", "switch", + "case", "default", "namespace", "not", "and", "or", + "bool", }; keywords_.insert(std::begin(keywords), std::end(keywords)); } @@ -66,7 +68,8 @@ class LobsterGenerator : public BaseGenerator { std::string LobsterType(const Type &type) { if (IsFloat(type.base_type)) return "float"; - if (IsScalar(type.base_type) && type.enum_def) return NormalizedName(*type.enum_def); + if (IsScalar(type.base_type) && type.enum_def) + return NormalizedName(*type.enum_def); if (!IsScalar(type.base_type)) return "flatbuffers_offset"; return "int"; } @@ -74,14 +77,14 @@ class LobsterGenerator : public BaseGenerator { // Returns the method name for use with add/put calls. std::string GenMethod(const Type &type) { return IsScalar(type.base_type) - ? MakeCamel(GenTypeBasic(type)) - : (IsStruct(type) ? "Struct" : "UOffsetTRelative"); + ? MakeCamel(GenTypeBasic(type)) + : (IsStruct(type) ? "Struct" : "UOffsetTRelative"); } // This uses Python names for now.. std::string GenTypeBasic(const Type &type) { static const char *ctypename[] = { - // clang-format off + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ #PTYPE, @@ -93,8 +96,8 @@ class LobsterGenerator : public BaseGenerator { } // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, nullptr, " "); std::string &code = *code_ptr; auto offsets = NumToString(field.value.offset); @@ -102,13 +105,12 @@ class LobsterGenerator : public BaseGenerator { if (IsScalar(field.value.type.base_type)) { std::string acc; if (struct_def.fixed) { - acc = "buf_.read_" + GenTypeName(field.value.type) + - "_le(pos_ + " + offsets + ")"; + acc = "buf_.read_" + GenTypeName(field.value.type) + "_le(pos_ + " + + offsets + ")"; } else { - acc = "buf_.flatbuffers_field_" + - GenTypeName(field.value.type) + "(pos_, " + offsets + ", " + - field.value.constant + ")"; + acc = "buf_.flatbuffers_field_" + GenTypeName(field.value.type) + + "(pos_, " + offsets + ", " + field.value.constant + ")"; } if (field.value.type.enum_def) acc = NormalizedName(*field.value.type.enum_def) + "(" + acc + ")"; @@ -130,7 +132,8 @@ class LobsterGenerator : public BaseGenerator { break; } case BASE_TYPE_STRING: - code += def + "():\n return buf_.flatbuffers_field_string(pos_, " + + code += def + + "():\n return buf_.flatbuffers_field_string(pos_, " + offsets + ")\n"; break; case BASE_TYPE_VECTOR: { @@ -171,19 +174,20 @@ class LobsterGenerator : public BaseGenerator { } if (field.value.type.base_type == BASE_TYPE_VECTOR) { code += def + - "_length():\n return buf_.flatbuffers_field_vector_len(pos_, " + + "_length():\n return " + "buf_.flatbuffers_field_vector_len(pos_, " + offsets + ")\n"; } } // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "struct " + NormalizedName(struct_def) + "Builder:\n b_:flatbuffers_builder\n"; code += " def start():\n b_.StartObject(" + - NumToString(struct_def.fields.vec.size()) + ")\n return this\n"; + NumToString(struct_def.fields.vec.size()) + + ")\n return this\n"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto &field = **it; @@ -209,8 +213,8 @@ class LobsterGenerator : public BaseGenerator { auto vector_type = field.value.type.VectorType(); auto alignment = InlineAlignment(vector_type); auto elem_size = InlineSize(vector_type); - code += NumToString(elem_size) + ", n_, " + NumToString(alignment) + - ")\n"; + code += + NumToString(elem_size) + ", n_, " + NumToString(alignment) + ")\n"; if (vector_type.base_type != BASE_TYPE_STRUCT || !vector_type.struct_def->fixed) { code += "def " + NormalizedName(struct_def) + "Create" + @@ -218,8 +222,7 @@ class LobsterGenerator : public BaseGenerator { "Vector(b_:flatbuffers_builder, v_:[" + LobsterType(vector_type) + "]):\n b_.StartVector(" + NumToString(elem_size) + ", v_.length, " + - NumToString(alignment) + - ")\n reverse(v_) e_: b_.Prepend" + + NumToString(alignment) + ")\n reverse(v_) e_: b_.Prepend" + GenMethod(vector_type) + "(e_)\n return b_.EndVector(v_.length)\n"; } @@ -243,7 +246,7 @@ class LobsterGenerator : public BaseGenerator { GenComment(struct_def.doc_comment, code_ptr, nullptr, ""); code += "class " + NormalizedName(struct_def) + " : flatbuffers_handle\n"; for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; GenStructAccessor(struct_def, field, code_ptr); @@ -252,8 +255,8 @@ class LobsterGenerator : public BaseGenerator { if (!struct_def.fixed) { // Generate a special accessor for the table that has been declared as // the root type. - code += "def GetRootAs" + NormalizedName(struct_def) + "(buf:string): return " + - NormalizedName(struct_def) + + code += "def GetRootAs" + NormalizedName(struct_def) + + "(buf:string): return " + NormalizedName(struct_def) + " { buf, buf.flatbuffers_indirect(0) }\n\n"; } if (struct_def.fixed) { @@ -283,8 +286,8 @@ class LobsterGenerator : public BaseGenerator { // Recursively generate arguments for a constructor, to deal with nested // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { auto &field = **it; @@ -293,7 +296,8 @@ class LobsterGenerator : public BaseGenerator { // don't clash, and to make it obvious these arguments are constructing // a nested struct, prefix the name with the field name. StructBuilderArgs(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); } else { std::string &code = *code_ptr; code += ", " + (nameprefix + NormalizedName(field)) + ":" + @@ -304,8 +308,8 @@ class LobsterGenerator : public BaseGenerator { // Recursively generate struct construction statements and instert manual // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { std::string &code = *code_ptr; code += " b_.Prep(" + NumToString(struct_def.minalign) + ", " + NumToString(struct_def.bytesize) + ")\n"; @@ -316,7 +320,8 @@ class LobsterGenerator : public BaseGenerator { code += " b_.Pad(" + NumToString(field.padding) + ")\n"; if (IsStruct(field.value.type)) { StructBuilderBody(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); } else { code += " b_.Prepend" + GenMethod(field.value.type) + "(" + nameprefix + NormalizedName(field) + ")\n"; @@ -325,11 +330,10 @@ class LobsterGenerator : public BaseGenerator { } // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; - code += "def Create" + NormalizedName(struct_def) + - "(b_:flatbuffers_builder"; + code += + "def Create" + NormalizedName(struct_def) + "(b_:flatbuffers_builder"; StructBuilderArgs(struct_def, "", code_ptr); code += "):\n"; StructBuilderBody(struct_def, "", code_ptr); @@ -363,8 +367,8 @@ class LobsterGenerator : public BaseGenerator { auto &struct_def = **it; GenStruct(struct_def, &code); } - return SaveFile((path_ + file_name_ + "_generated.lobster").c_str(), - code, false); + return SaveFile((path_ + file_name_ + "_generated.lobster").c_str(), code, + false); } private: @@ -375,7 +379,7 @@ class LobsterGenerator : public BaseGenerator { } // namespace lobster bool GenerateLobster(const Parser &parser, const std::string &path, - const std::string &file_name) { + const std::string &file_name) { lobster::LobsterGenerator generator(parser, path, file_name); return generator.generate(); } diff --git a/src/idl_gen_lua.cpp b/src/idl_gen_lua.cpp index 10df2311..6ae7dd4c 100644 --- a/src/idl_gen_lua.cpp +++ b/src/idl_gen_lua.cpp @@ -14,716 +14,710 @@ * limitations under the License. */ - // independent from idl_parser, since this code is not needed for most clients +// independent from idl_parser, since this code is not needed for most clients #include <string> +#include <unordered_set> #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { namespace lua { - // Hardcode spaces per indentation. - const CommentConfig def_comment = { nullptr, "--", nullptr }; - const char * Indent = " "; - const char * Comment = "-- "; - const char * End = "end\n"; - const char * EndFunc = "end\n"; - const char * SelfData = "self.view"; - const char * SelfDataPos = "self.view.pos"; - const char * SelfDataBytes = "self.view.bytes"; - - class LuaGenerator : public BaseGenerator { - public: - LuaGenerator(const Parser &parser, const std::string &path, - const std::string &file_name) +// Hardcode spaces per indentation. +const CommentConfig def_comment = { nullptr, "--", nullptr }; +const char *Indent = " "; +const char *Comment = "-- "; +const char *End = "end\n"; +const char *EndFunc = "end\n"; +const char *SelfData = "self.view"; +const char *SelfDataPos = "self.view.pos"; +const char *SelfDataBytes = "self.view.bytes"; + +class LuaGenerator : public BaseGenerator { + public: + LuaGenerator(const Parser &parser, const std::string &path, + const std::string &file_name) : BaseGenerator(parser, path, file_name, "" /* not used */, - "" /* not used */) { - static const char * const keywords[] = { - "and", - "break", - "do", - "else", - "elseif", - "end", - "false", - "for", - "function", - "goto", - "if", - "in", - "local", - "nil", - "not", - "or", - "repeat", - "return", - "then", - "true", - "until", - "while" - }; - keywords_.insert(std::begin(keywords), std::end(keywords)); - } - - // Most field accessors need to retrieve and test the field offset first, - // this is the prefix code for that. - std::string OffsetPrefix(const FieldDef &field) { - return std::string(Indent) + - "local o = " + SelfData + ":Offset(" + NumToString(field.value.offset) + ")\n" + - Indent + "if o ~= 0 then\n"; - } - - // Begin a class declaration. - void BeginClass(const StructDef &struct_def, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "local " + NormalizedName(struct_def) + " = {} -- the module\n"; - code += "local " + NormalizedMetaName(struct_def) + " = {} -- the class metatable\n"; - code += "\n"; - } - - // Begin enum code with a class declaration. - void BeginEnum(const std::string &class_name, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "local " + class_name + " = {\n"; - } - - std::string EscapeKeyword(const std::string &name) const { - return keywords_.find(name) == keywords_.end() ? name : "_" + name; - } - - std::string NormalizedName(const Definition &definition) const { - return EscapeKeyword(definition.name); - } - - std::string NormalizedName(const EnumVal &ev) const { - return EscapeKeyword(ev.name); - } - - std::string NormalizedMetaName(const Definition &definition) const { - return EscapeKeyword(definition.name) + "_mt"; - } - - // A single enum member. - void EnumMember(const EnumDef &enum_def, const EnumVal &ev, std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + NormalizedName(ev) + " = " + - enum_def.ToString(ev) + ",\n"; - } - - // End enum code. - void EndEnum(std::string *code_ptr) { - std::string &code = *code_ptr; - code += "}\n"; - } - - void GenerateNewObjectPrototype(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".New()\n"; - code += std::string(Indent) + "local o = {}\n"; - code += std::string(Indent) + "setmetatable(o, {__index = " + NormalizedMetaName(struct_def) + "})\n"; - code += std::string(Indent) + "return o\n"; - code += EndFunc; - } - - // Initialize a new struct or table from existing data. - void NewRootTypeFromBuffer(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".GetRootAs" + NormalizedName(struct_def) + "(buf, offset)\n"; - code += std::string(Indent) + "local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n"; - code += std::string(Indent) + "local o = " + NormalizedName(struct_def) + ".New()\n"; - code += std::string(Indent) + "o:Init(buf, n + offset)\n"; - code += std::string(Indent) + "return o\n"; - code += EndFunc; - } - - // Initialize an existing object with other data, to avoid an allocation. - void InitializeExisting(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - GenReceiver(struct_def, code_ptr); - code += "Init(buf, pos)\n"; - code += std::string(Indent) + SelfData + " = flatbuffers.view.New(buf, pos)\n"; - code += EndFunc; - } - - // Get the length of a vector. - void GetVectorLen(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)) + "Length()\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n"; - code += std::string(Indent) + End; + "" /* not used */) { + static const char *const keywords[] = { + "and", "break", "do", "else", "elseif", "end", "false", "for", + "function", "goto", "if", "in", "local", "nil", "not", "or", + "repeat", "return", "then", "true", "until", "while" + }; + keywords_.insert(std::begin(keywords), std::end(keywords)); + } + + // Most field accessors need to retrieve and test the field offset first, + // this is the prefix code for that. + std::string OffsetPrefix(const FieldDef &field) { + return std::string(Indent) + "local o = " + SelfData + ":Offset(" + + NumToString(field.value.offset) + ")\n" + Indent + + "if o ~= 0 then\n"; + } + + // Begin a class declaration. + void BeginClass(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "local " + NormalizedName(struct_def) + " = {} -- the module\n"; + code += "local " + NormalizedMetaName(struct_def) + + " = {} -- the class metatable\n"; + code += "\n"; + } + + // Begin enum code with a class declaration. + void BeginEnum(const std::string &class_name, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "local " + class_name + " = {\n"; + } + + std::string EscapeKeyword(const std::string &name) const { + return keywords_.find(name) == keywords_.end() ? name : "_" + name; + } + + std::string NormalizedName(const Definition &definition) const { + return EscapeKeyword(definition.name); + } + + std::string NormalizedName(const EnumVal &ev) const { + return EscapeKeyword(ev.name); + } + + std::string NormalizedMetaName(const Definition &definition) const { + return EscapeKeyword(definition.name) + "_mt"; + } + + // A single enum member. + void EnumMember(const EnumDef &enum_def, const EnumVal &ev, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + NormalizedName(ev) + " = " + + enum_def.ToString(ev) + ",\n"; + } + + // End enum code. + void EndEnum(std::string *code_ptr) { + std::string &code = *code_ptr; + code += "}\n"; + } + + void GenerateNewObjectPrototype(const StructDef &struct_def, + std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".New()\n"; + code += std::string(Indent) + "local o = {}\n"; + code += std::string(Indent) + + "setmetatable(o, {__index = " + NormalizedMetaName(struct_def) + + "})\n"; + code += std::string(Indent) + "return o\n"; + code += EndFunc; + } + + // Initialize a new struct or table from existing data. + void NewRootTypeFromBuffer(const StructDef &struct_def, + std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".GetRootAs" + + NormalizedName(struct_def) + "(buf, offset)\n"; + code += std::string(Indent) + + "local n = flatbuffers.N.UOffsetT:Unpack(buf, offset)\n"; + code += std::string(Indent) + "local o = " + NormalizedName(struct_def) + + ".New()\n"; + code += std::string(Indent) + "o:Init(buf, n + offset)\n"; + code += std::string(Indent) + "return o\n"; + code += EndFunc; + } + + // Initialize an existing object with other data, to avoid an allocation. + void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + + GenReceiver(struct_def, code_ptr); + code += "Init(buf, pos)\n"; + code += + std::string(Indent) + SelfData + " = flatbuffers.view.New(buf, pos)\n"; + code += EndFunc; + } + + // Get the length of a vector. + void GetVectorLen(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)) + "Length()\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "return " + SelfData + ":VectorLen(o)\n"; + code += std::string(Indent) + End; + code += std::string(Indent) + "return 0\n"; + code += EndFunc; + } + + // Get the value of a struct's scalar. + void GetScalarFieldOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + std::string getter = GenGetter(field.value.type); + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += std::string(Indent) + "return " + getter; + code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) + + ")\n"; + code += EndFunc; + } + + // Get the value of a table's scalar. + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + std::string getter = GenGetter(field.value.type); + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + getter += std::string("o + ") + SelfDataPos + ")"; + auto is_bool = field.value.type.base_type == BASE_TYPE_BOOL; + if (is_bool) { getter = "(" + getter + " ~= 0)"; } + code += std::string(Indent) + Indent + "return " + getter + "\n"; + code += std::string(Indent) + End; + std::string default_value; + if (is_bool) { + default_value = field.value.constant == "0" ? "false" : "true"; + } else { + default_value = field.value.constant; + } + code += std::string(Indent) + "return " + default_value + "\n"; + code += EndFunc; + } + + // Get a struct by initializing an existing struct. + // Specific to Struct. + void GetStructFieldOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(obj)\n"; + code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " + + SelfDataPos + " + "; + code += NumToString(field.value.offset) + ")\n"; + code += std::string(Indent) + "return obj\n"; + code += EndFunc; + } + + // Get a struct by initializing an existing struct. + // Specific to Table. + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + if (field.value.type.struct_def->fixed) { + code += + std::string(Indent) + Indent + "local x = o + " + SelfDataPos + "\n"; + } else { + code += std::string(Indent) + Indent + "local x = " + SelfData + + ":Indirect(o + " + SelfDataPos + ")\n"; + } + code += std::string(Indent) + Indent + "local obj = require('" + + TypeNameWithNamespace(field) + "').New()\n"; + code += + std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a string. + void GetStringField(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "()\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "return " + GenGetter(field.value.type); + code += std::string("o + ") + SelfDataPos + ")\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a union from an object. + void GetUnionField(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)) + "()\n"; + code += OffsetPrefix(field); + + // TODO(rw): this works and is not the good way to it: + // bool is_native_table = TypeName(field) == "*flatbuffers.Table"; + // if (is_native_table) { + // code += std::string(Indent) + Indent + "from flatbuffers.table import + // Table\n"; + //} else { + // code += std::string(Indent) + Indent + + // code += "from ." + TypeName(field) + " import " + TypeName(field) + + // "\n"; + //} + code += + std::string(Indent) + Indent + + "local obj = " + "flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)\n"; + code += std::string(Indent) + Indent + GenGetter(field.value.type) + + "obj, o)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a vector's struct member. + void GetMemberOfVectorOfStruct(const StructDef &struct_def, + const FieldDef &field, std::string *code_ptr) { + std::string &code = *code_ptr; + auto vectortype = field.value.type.VectorType(); + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(j)\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "local x = " + SelfData + ":Vector(o)\n"; + code += std::string(Indent) + Indent + "x = x + ((j-1) * "; + code += NumToString(InlineSize(vectortype)) + ")\n"; + if (!(vectortype.struct_def->fixed)) { + code += + std::string(Indent) + Indent + "x = " + SelfData + ":Indirect(x)\n"; + } + code += std::string(Indent) + Indent + "local obj = require('" + + TypeNameWithNamespace(field) + "').New()\n"; + code += + std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; + code += std::string(Indent) + Indent + "return obj\n"; + code += std::string(Indent) + End; + code += EndFunc; + } + + // Get the value of a vector's non-struct member. Uses a named return + // argument to conveniently set the zero value for the result. + void GetMemberOfVectorOfNonStruct(const StructDef &struct_def, + const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + auto vectortype = field.value.type.VectorType(); + + GenReceiver(struct_def, code_ptr); + code += MakeCamel(NormalizedName(field)); + code += "(j)\n"; + code += OffsetPrefix(field); + code += + std::string(Indent) + Indent + "local a = " + SelfData + ":Vector(o)\n"; + code += std::string(Indent) + Indent; + code += "return " + GenGetter(field.value.type); + code += "a + ((j-1) * "; + code += NumToString(InlineSize(vectortype)) + "))\n"; + code += std::string(Indent) + End; + if (vectortype.base_type == BASE_TYPE_STRING) { + code += std::string(Indent) + "return ''\n"; + } else { code += std::string(Indent) + "return 0\n"; - code += EndFunc; - } - - // Get the value of a struct's scalar. - void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - std::string getter = GenGetter(field.value.type); - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += std::string(Indent) + "return " + getter; - code += std::string(SelfDataPos) + " + " + NumToString(field.value.offset) + ")\n"; - code += EndFunc; } - - // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - std::string getter = GenGetter(field.value.type); - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - getter += std::string("o + ") + SelfDataPos + ")"; - auto is_bool = field.value.type.base_type == BASE_TYPE_BOOL; - if (is_bool) { - getter = "(" + getter + " ~= 0)"; - } - code += std::string(Indent) + Indent + "return " + getter + "\n"; - code += std::string(Indent) + End; - std::string default_value; - if (is_bool) { - default_value = field.value.constant == "0" ? "false" : "true"; - } - else { - default_value = field.value.constant; - } - code += std::string(Indent) + "return " + default_value + "\n"; - code += EndFunc; - } - - // Get a struct by initializing an existing struct. - // Specific to Struct. - void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(obj)\n"; - code += std::string(Indent) + "obj:Init(" + SelfDataBytes + ", " + SelfDataPos + " + "; - code += NumToString(field.value.offset) + ")\n"; - code += std::string(Indent) + "return obj\n"; - code += EndFunc; - } - - // Get a struct by initializing an existing struct. - // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - if (field.value.type.struct_def->fixed) { - code += std::string(Indent) + Indent + "local x = o + " + SelfDataPos + "\n"; - } - else { - code += std::string(Indent) + Indent + "local x = " + SelfData + ":Indirect(o + " + SelfDataPos + ")\n"; + code += EndFunc; + } + + // Begin the creator function signature. + void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + + code += "function " + NormalizedName(struct_def) + ".Create" + + NormalizedName(struct_def); + code += "(builder"; + } + + // Recursively generate arguments for a constructor, to deal with nested + // structs. + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (IsStruct(field.value.type)) { + // Generate arguments for a struct inside a struct. To ensure names + // don't clash, and to make it obvious these arguments are constructing + // a nested struct, prefix the name with the field name. + StructBuilderArgs(*field.value.type.struct_def, + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); + } else { + std::string &code = *code_ptr; + code += std::string(", ") + nameprefix; + code += MakeCamel(NormalizedName(field), false); } - code += std::string(Indent) + Indent + "local obj = require('" + TypeNameWithNamespace(field) + "').New()\n"; - code += std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; } - - // Get the value of a string. - void GetStringField(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "()\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "return " + GenGetter(field.value.type); - code += std::string("o + ") + SelfDataPos + ")\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a union from an object. - void GetUnionField(const StructDef &struct_def, const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)) + "()\n"; - code += OffsetPrefix(field); - - // TODO(rw): this works and is not the good way to it: - //bool is_native_table = TypeName(field) == "*flatbuffers.Table"; - //if (is_native_table) { - // code += std::string(Indent) + Indent + "from flatbuffers.table import Table\n"; - //} else { - // code += std::string(Indent) + Indent + - // code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n"; - //} - code += std::string(Indent) + Indent + "local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0)\n"; - code += std::string(Indent) + Indent + GenGetter(field.value.type) + "obj, o)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a vector's struct member. - void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - auto vectortype = field.value.type.VectorType(); - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(j)\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "local x = " + SelfData + ":Vector(o)\n"; - code += std::string(Indent) + Indent + "x = x + ((j-1) * "; - code += NumToString(InlineSize(vectortype)) + ")\n"; - if (!(vectortype.struct_def->fixed)) { - code += std::string(Indent) + Indent + "x = " + SelfData + ":Indirect(x)\n"; - } - code += std::string(Indent) + Indent + "local obj = require('" + TypeNameWithNamespace(field) + "').New()\n"; - code += std::string(Indent) + Indent + "obj:Init(" + SelfDataBytes + ", x)\n"; - code += std::string(Indent) + Indent + "return obj\n"; - code += std::string(Indent) + End; - code += EndFunc; - } - - // Get the value of a vector's non-struct member. Uses a named return - // argument to conveniently set the zero value for the result. - void GetMemberOfVectorOfNonStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { - std::string &code = *code_ptr; - auto vectortype = field.value.type.VectorType(); - - GenReceiver(struct_def, code_ptr); - code += MakeCamel(NormalizedName(field)); - code += "(j)\n"; - code += OffsetPrefix(field); - code += std::string(Indent) + Indent + "local a = " + SelfData + ":Vector(o)\n"; - code += std::string(Indent) + Indent; - code += "return " + GenGetter(field.value.type); - code += "a + ((j-1) * "; - code += NumToString(InlineSize(vectortype)) + "))\n"; - code += std::string(Indent) + End; - if (vectortype.base_type == BASE_TYPE_STRING) { - code += std::string(Indent) + "return ''\n"; - } - else { - code += std::string(Indent) + "return 0\n"; - } - code += EndFunc; - } - - // Begin the creator function signature. - void BeginBuilderArgs(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - - code += "function " + NormalizedName(struct_def) + ".Create" + NormalizedName(struct_def); - code += "(builder"; - } - - // Recursively generate arguments for a constructor, to deal with nested - // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (IsStruct(field.value.type)) { - // Generate arguments for a struct inside a struct. To ensure names - // don't clash, and to make it obvious these arguments are constructing - // a nested struct, prefix the name with the field name. - StructBuilderArgs(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); - } - else { - std::string &code = *code_ptr; - code += std::string(", ") + nameprefix; - code += MakeCamel(NormalizedName(field), false); - } - } - } - - // End the creator function signature. - void EndBuilderArgs(std::string *code_ptr) { - std::string &code = *code_ptr; - code += ")\n"; - } - - // Recursively generate struct construction statements and instert manual - // padding. - void StructBuilderBody(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + "builder:Prep(" + NumToString(struct_def.minalign) + ", "; - code += NumToString(struct_def.bytesize) + ")\n"; - for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); ++it) { - auto &field = **it; - if (field.padding) - code += std::string(Indent) + "builder:Pad(" + NumToString(field.padding) + ")\n"; - if (IsStruct(field.value.type)) { - StructBuilderBody(*field.value.type.struct_def, - (nameprefix + (NormalizedName(field) + "_")).c_str(), code_ptr); - } - else { - code += std::string(Indent) + "builder:Prepend" + GenMethod(field) + "("; - code += nameprefix + MakeCamel(NormalizedName(field), false) + ")\n"; - } + } + + // End the creator function signature. + void EndBuilderArgs(std::string *code_ptr) { + std::string &code = *code_ptr; + code += ")\n"; + } + + // Recursively generate struct construction statements and instert manual + // padding. + void StructBuilderBody(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + "builder:Prep(" + + NumToString(struct_def.minalign) + ", "; + code += NumToString(struct_def.bytesize) + ")\n"; + for (auto it = struct_def.fields.vec.rbegin(); + it != struct_def.fields.vec.rend(); ++it) { + auto &field = **it; + if (field.padding) + code += std::string(Indent) + "builder:Pad(" + + NumToString(field.padding) + ")\n"; + if (IsStruct(field.value.type)) { + StructBuilderBody(*field.value.type.struct_def, + (nameprefix + (NormalizedName(field) + "_")).c_str(), + code_ptr); + } else { + code += + std::string(Indent) + "builder:Prepend" + GenMethod(field) + "("; + code += nameprefix + MakeCamel(NormalizedName(field), false) + ")\n"; } } - - void EndBuilderBody(std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Indent) + "return builder:Offset()\n"; - code += EndFunc; - } - - // Get the value of a table's starting offset. - void GetStartOfTable(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Start"; - code += "(builder) "; - code += "builder:StartObject("; - code += NumToString(struct_def.fields.vec.size()); - code += ") end\n"; - } - - // Set the value of a table's field. - void BuildFieldOfTable(const StructDef &struct_def, - const FieldDef &field, const size_t offset, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Add" + MakeCamel(NormalizedName(field)); - code += "(builder, "; - code += MakeCamel(NormalizedName(field), false); - code += ") "; - code += "builder:Prepend"; - code += GenMethod(field) + "Slot("; - code += NumToString(offset) + ", "; - // todo: i don't need to cast in Lua, but am I missing something? + } + + void EndBuilderBody(std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Indent) + "return builder:Offset()\n"; + code += EndFunc; + } + + // Get the value of a table's starting offset. + void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Start"; + code += "(builder) "; + code += "builder:StartObject("; + code += NumToString(struct_def.fields.vec.size()); + code += ") end\n"; + } + + // Set the value of a table's field. + void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field, + const size_t offset, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Add" + + MakeCamel(NormalizedName(field)); + code += "(builder, "; + code += MakeCamel(NormalizedName(field), false); + code += ") "; + code += "builder:Prepend"; + code += GenMethod(field) + "Slot("; + code += NumToString(offset) + ", "; + // todo: i don't need to cast in Lua, but am I missing something? // if (!IsScalar(field.value.type.base_type) && (!struct_def.fixed)) { // code += "flatbuffers.N.UOffsetTFlags.py_type"; // code += "("; // code += MakeCamel(NormalizedName(field), false) + ")"; // } else { - code += MakeCamel(NormalizedName(field), false); - // } - code += ", " + field.value.constant; - code += ") end\n"; - } - - // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".Start"; - code += MakeCamel(NormalizedName(field)); - code += "Vector(builder, numElems) return builder:StartVector("; - auto vector_type = field.value.type.VectorType(); - auto alignment = InlineAlignment(vector_type); - auto elem_size = InlineSize(vector_type); - code += NumToString(elem_size); - code += ", numElems, " + NumToString(alignment); - code += ") end\n"; - } - - // Get the offset of the end of a table. - void GetEndOffsetOnTable(const StructDef &struct_def, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedName(struct_def) + ".End"; - code += "(builder) "; - code += "return builder:EndObject() end\n"; - } - - // Generate the receiver for function signatures. - void GenReceiver(const StructDef &struct_def, std::string *code_ptr) { - std::string &code = *code_ptr; - code += "function " + NormalizedMetaName(struct_def) + ":"; - } - - // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { - GenComment(field.doc_comment, code_ptr, &def_comment); - if (IsScalar(field.value.type.base_type)) { - if (struct_def.fixed) { - GetScalarFieldOfStruct(struct_def, field, code_ptr); - } - else { - GetScalarFieldOfTable(struct_def, field, code_ptr); - } + code += MakeCamel(NormalizedName(field), false); + // } + code += ", " + field.value.constant; + code += ") end\n"; + } + + // Set the value of one of the members of a table's vector. + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".Start"; + code += MakeCamel(NormalizedName(field)); + code += "Vector(builder, numElems) return builder:StartVector("; + auto vector_type = field.value.type.VectorType(); + auto alignment = InlineAlignment(vector_type); + auto elem_size = InlineSize(vector_type); + code += NumToString(elem_size); + code += ", numElems, " + NumToString(alignment); + code += ") end\n"; + } + + // Get the offset of the end of a table. + void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedName(struct_def) + ".End"; + code += "(builder) "; + code += "return builder:EndObject() end\n"; + } + + // Generate the receiver for function signatures. + void GenReceiver(const StructDef &struct_def, std::string *code_ptr) { + std::string &code = *code_ptr; + code += "function " + NormalizedMetaName(struct_def) + ":"; + } + + // Generate a struct field, conditioned on its child type(s). + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { + GenComment(field.doc_comment, code_ptr, &def_comment); + if (IsScalar(field.value.type.base_type)) { + if (struct_def.fixed) { + GetScalarFieldOfStruct(struct_def, field, code_ptr); + } else { + GetScalarFieldOfTable(struct_def, field, code_ptr); } - else { - switch (field.value.type.base_type) { + } else { + switch (field.value.type.base_type) { case BASE_TYPE_STRUCT: if (struct_def.fixed) { GetStructFieldOfStruct(struct_def, field, code_ptr); - } - else { + } else { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { GetMemberOfVectorOfStruct(struct_def, field, code_ptr); - } - else { + } else { GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr); } break; } case BASE_TYPE_UNION: GetUnionField(struct_def, field, code_ptr); break; default: FLATBUFFERS_ASSERT(0); - } - } - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - GetVectorLen(struct_def, field, code_ptr); } } + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + GetVectorLen(struct_def, field, code_ptr); + } + } - // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { - GetStartOfTable(struct_def, code_ptr); + // Generate table constructors, conditioned on its members' types. + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { + GetStartOfTable(struct_def, code_ptr); - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; - auto offset = it - struct_def.fields.vec.begin(); - BuildFieldOfTable(struct_def, field, offset, code_ptr); - if (field.value.type.base_type == BASE_TYPE_VECTOR) { - BuildVectorOfTable(struct_def, field, code_ptr); - } + auto offset = it - struct_def.fields.vec.begin(); + BuildFieldOfTable(struct_def, field, offset, code_ptr); + if (field.value.type.base_type == BASE_TYPE_VECTOR) { + BuildVectorOfTable(struct_def, field, code_ptr); } - - GetEndOffsetOnTable(struct_def, code_ptr); } - // Generate struct or table methods. - void GenStruct(const StructDef &struct_def, std::string *code_ptr) { - if (struct_def.generated) return; + GetEndOffsetOnTable(struct_def, code_ptr); + } - GenComment(struct_def.doc_comment, code_ptr, &def_comment); - BeginClass(struct_def, code_ptr); + // Generate struct or table methods. + void GenStruct(const StructDef &struct_def, std::string *code_ptr) { + if (struct_def.generated) return; - GenerateNewObjectPrototype(struct_def, code_ptr); + GenComment(struct_def.doc_comment, code_ptr, &def_comment); + BeginClass(struct_def, code_ptr); - if (!struct_def.fixed) { - // Generate a special accessor for the table that has been declared as - // the root type. - NewRootTypeFromBuffer(struct_def, code_ptr); - } + GenerateNewObjectPrototype(struct_def, code_ptr); - // Generate the Init method that sets the field in a pre-existing - // accessor object. This is to allow object reuse. - InitializeExisting(struct_def, code_ptr); - for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { - auto &field = **it; - if (field.deprecated) continue; + if (!struct_def.fixed) { + // Generate a special accessor for the table that has been declared as + // the root type. + NewRootTypeFromBuffer(struct_def, code_ptr); + } - GenStructAccessor(struct_def, field, code_ptr); - } + // Generate the Init method that sets the field in a pre-existing + // accessor object. This is to allow object reuse. + InitializeExisting(struct_def, code_ptr); + for (auto it = struct_def.fields.vec.begin(); + it != struct_def.fields.vec.end(); ++it) { + auto &field = **it; + if (field.deprecated) continue; - if (struct_def.fixed) { - // create a struct constructor function - GenStructBuilder(struct_def, code_ptr); - } - else { - // Create a set of functions that allow table construction. - GenTableBuilders(struct_def, code_ptr); - } + GenStructAccessor(struct_def, field, code_ptr); } - // Generate enum declarations. - void GenEnum(const EnumDef &enum_def, std::string *code_ptr) { - if (enum_def.generated) return; - - GenComment(enum_def.doc_comment, code_ptr, &def_comment); - BeginEnum(NormalizedName(enum_def), code_ptr); - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); - ++it) { - auto &ev = **it; - GenComment(ev.doc_comment, code_ptr, &def_comment, Indent); - EnumMember(enum_def, ev, code_ptr); - } - EndEnum(code_ptr); + if (struct_def.fixed) { + // create a struct constructor function + GenStructBuilder(struct_def, code_ptr); + } else { + // Create a set of functions that allow table construction. + GenTableBuilders(struct_def, code_ptr); } + } + + // Generate enum declarations. + void GenEnum(const EnumDef &enum_def, std::string *code_ptr) { + if (enum_def.generated) return; - // Returns the function name that is able to read a value of the given type. - std::string GenGetter(const Type &type) { - switch (type.base_type) { + GenComment(enum_def.doc_comment, code_ptr, &def_comment); + BeginEnum(NormalizedName(enum_def), code_ptr); + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { + auto &ev = **it; + GenComment(ev.doc_comment, code_ptr, &def_comment, Indent); + EnumMember(enum_def, ev, code_ptr); + } + EndEnum(code_ptr); + } + + // Returns the function name that is able to read a value of the given type. + std::string GenGetter(const Type &type) { + switch (type.base_type) { case BASE_TYPE_STRING: return std::string(SelfData) + ":String("; - case BASE_TYPE_UNION: return std::string(SelfData) + ":Union("; + case BASE_TYPE_UNION: return std::string(SelfData) + ":Union("; case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); default: return std::string(SelfData) + ":Get(flatbuffers.N." + - MakeCamel(GenTypeGet(type)) + ", "; - } + MakeCamel(GenTypeGet(type)) + ", "; } + } - // Returns the method name for use with add/put calls. - std::string GenMethod(const FieldDef &field) { - return IsScalar(field.value.type.base_type) - ? MakeCamel(GenTypeBasic(field.value.type)) - : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative"); - } + // Returns the method name for use with add/put calls. + std::string GenMethod(const FieldDef &field) { + return IsScalar(field.value.type.base_type) + ? MakeCamel(GenTypeBasic(field.value.type)) + : (IsStruct(field.value.type) ? "Struct" : "UOffsetTRelative"); + } - std::string GenTypeBasic(const Type &type) { - static const char *ctypename[] = { - // clang-format off + std::string GenTypeBasic(const Type &type) { + static const char *ctypename[] = { + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ #PTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD - // clang-format on - }; - return ctypename[type.base_type]; - } + // clang-format on + }; + return ctypename[type.base_type]; + } - std::string GenTypePointer(const Type &type) { - switch (type.base_type) { + std::string GenTypePointer(const Type &type) { + switch (type.base_type) { case BASE_TYPE_STRING: return "string"; case BASE_TYPE_VECTOR: return GenTypeGet(type.VectorType()); case BASE_TYPE_STRUCT: return type.struct_def->name; case BASE_TYPE_UNION: // fall through default: return "*flatbuffers.Table"; - } - } - - std::string GenTypeGet(const Type &type) { - return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); - } - - std::string GetNamespace(const Type &type) { - return type.struct_def->defined_namespace->GetFullyQualifiedName(type.struct_def->name); - } - - std::string TypeName(const FieldDef &field) { - return GenTypeGet(field.value.type); - } - - std::string TypeNameWithNamespace(const FieldDef &field) { - return GetNamespace(field.value.type); - } - - // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { - BeginBuilderArgs(struct_def, code_ptr); - StructBuilderArgs(struct_def, "", code_ptr); - EndBuilderArgs(code_ptr); - - StructBuilderBody(struct_def, "", code_ptr); - EndBuilderBody(code_ptr); } - - bool generate() { - if (!generateEnums()) return false; - if (!generateStructs()) return false; - return true; - } - - private: - bool generateEnums() { - for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end(); - ++it) { - auto &enum_def = **it; - std::string enumcode; - GenEnum(enum_def, &enumcode); - if (!SaveType(enum_def, enumcode, false)) return false; - } - return true; - } - - bool generateStructs() { - for (auto it = parser_.structs_.vec.begin(); - it != parser_.structs_.vec.end(); ++it) { - auto &struct_def = **it; - std::string declcode; - GenStruct(struct_def, &declcode); - if (!SaveType(struct_def, declcode, true)) return false; - } - return true; - } - - // Begin by declaring namespace and imports. - void BeginFile(const std::string &name_space_name, const bool needs_imports, - std::string *code_ptr) { - std::string &code = *code_ptr; - code += std::string(Comment) + FlatBuffersGeneratedWarning() + "\n\n"; - code += std::string(Comment) + "namespace: " + name_space_name + "\n\n"; - if (needs_imports) { - code += "local flatbuffers = require('flatbuffers')\n\n"; - } - } - - // Save out the generated code for a Lua Table type. - bool SaveType(const Definition &def, const std::string &classcode, - bool needs_imports) { - if (!classcode.length()) return true; - - std::string namespace_dir = path_; - auto &namespaces = def.defined_namespace->components; - for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { - if (it != namespaces.begin()) namespace_dir += kPathSeparator; - namespace_dir += *it; - //std::string init_py_filename = namespace_dir + "/__init__.py"; - //SaveFile(init_py_filename.c_str(), "", false); - } - - std::string code = ""; - BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code); - code += classcode; - code += "\n"; - code += "return " + NormalizedName(def) + " " + Comment + "return the module"; - std::string filename = + } + + std::string GenTypeGet(const Type &type) { + return IsScalar(type.base_type) ? GenTypeBasic(type) : GenTypePointer(type); + } + + std::string GetNamespace(const Type &type) { + return type.struct_def->defined_namespace->GetFullyQualifiedName( + type.struct_def->name); + } + + std::string TypeName(const FieldDef &field) { + return GenTypeGet(field.value.type); + } + + std::string TypeNameWithNamespace(const FieldDef &field) { + return GetNamespace(field.value.type); + } + + // Create a struct with a builder and the struct's arguments. + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { + BeginBuilderArgs(struct_def, code_ptr); + StructBuilderArgs(struct_def, "", code_ptr); + EndBuilderArgs(code_ptr); + + StructBuilderBody(struct_def, "", code_ptr); + EndBuilderBody(code_ptr); + } + + bool generate() { + if (!generateEnums()) return false; + if (!generateStructs()) return false; + return true; + } + + private: + bool generateEnums() { + for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end(); + ++it) { + auto &enum_def = **it; + std::string enumcode; + GenEnum(enum_def, &enumcode); + if (!SaveType(enum_def, enumcode, false)) return false; + } + return true; + } + + bool generateStructs() { + for (auto it = parser_.structs_.vec.begin(); + it != parser_.structs_.vec.end(); ++it) { + auto &struct_def = **it; + std::string declcode; + GenStruct(struct_def, &declcode); + if (!SaveType(struct_def, declcode, true)) return false; + } + return true; + } + + // Begin by declaring namespace and imports. + void BeginFile(const std::string &name_space_name, const bool needs_imports, + std::string *code_ptr) { + std::string &code = *code_ptr; + code += std::string(Comment) + FlatBuffersGeneratedWarning() + "\n\n"; + code += std::string(Comment) + "namespace: " + name_space_name + "\n\n"; + if (needs_imports) { + code += "local flatbuffers = require('flatbuffers')\n\n"; + } + } + + // Save out the generated code for a Lua Table type. + bool SaveType(const Definition &def, const std::string &classcode, + bool needs_imports) { + if (!classcode.length()) return true; + + std::string namespace_dir = path_; + auto &namespaces = def.defined_namespace->components; + for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { + if (it != namespaces.begin()) namespace_dir += kPathSeparator; + namespace_dir += *it; + // std::string init_py_filename = namespace_dir + "/__init__.py"; + // SaveFile(init_py_filename.c_str(), "", false); + } + + std::string code = ""; + BeginFile(LastNamespacePart(*def.defined_namespace), needs_imports, &code); + code += classcode; + code += "\n"; + code += + "return " + NormalizedName(def) + " " + Comment + "return the module"; + std::string filename = NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".lua"; - return SaveFile(filename.c_str(), code, false); - } - private: - std::unordered_set<std::string> keywords_; - }; + return SaveFile(filename.c_str(), code, false); + } + + private: + std::unordered_set<std::string> keywords_; +}; } // namespace lua bool GenerateLua(const Parser &parser, const std::string &path, - const std::string &file_name) { + const std::string &file_name) { lua::LuaGenerator generator(parser, path, file_name); return generator.generate(); } diff --git a/src/idl_gen_php.cpp b/src/idl_gen_php.cpp index 9d814159..16e47816 100644 --- a/src/idl_gen_php.cpp +++ b/src/idl_gen_php.cpp @@ -826,7 +826,8 @@ class PhpGenerator : public BaseGenerator { code += Indent + "private static $names = array(\n"; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { auto &ev = **it; - code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" + ev.name + "\",\n"; + code += Indent + Indent + enum_def.name + "::" + ev.name + "=>" + "\"" + + ev.name + "\",\n"; } code += Indent + ");\n\n"; diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp index c8db3597..bff0d849 100644 --- a/src/idl_gen_python.cpp +++ b/src/idl_gen_python.cpp @@ -17,14 +17,13 @@ // independent from idl_parser, since this code is not needed for most clients #include <string> +#include <unordered_set> #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include <unordered_set> - namespace flatbuffers { namespace python { @@ -39,40 +38,12 @@ class PythonGenerator : public BaseGenerator { : BaseGenerator(parser, path, file_name, "" /* not used */, "" /* not used */), float_const_gen_("float('nan')", "float('inf')", "float('-inf')") { - static const char * const keywords[] = { - "False", - "None", - "True", - "and", - "as", - "assert", - "break", - "class", - "continue", - "def", - "del", - "elif", - "else", - "except", - "finally", - "for", - "from", - "global", - "if", - "import", - "in", - "is", - "lambda", - "nonlocal", - "not", - "or", - "pass", - "raise", - "return", - "try", - "while", - "with", - "yield" + static const char *const keywords[] = { + "False", "None", "True", "and", "as", "assert", "break", + "class", "continue", "def", "del", "elif", "else", "except", + "finally", "for", "from", "global", "if", "import", "in", + "is", "lambda", "nonlocal", "not", "or", "pass", "raise", + "return", "try", "while", "with", "yield" }; keywords_.insert(std::begin(keywords), std::end(keywords)); } @@ -81,9 +52,9 @@ class PythonGenerator : public BaseGenerator { // this is the prefix code for that. std::string OffsetPrefix(const FieldDef &field) { return "\n" + Indent + Indent + - "o = flatbuffers.number_types.UOffsetTFlags.py_type" + - "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" + - Indent + Indent + "if o != 0:\n"; + "o = flatbuffers.number_types.UOffsetTFlags.py_type" + + "(self._tab.Offset(" + NumToString(field.value.offset) + "))\n" + + Indent + Indent + "if o != 0:\n"; } // Begin a class declaration. @@ -148,8 +119,7 @@ class PythonGenerator : public BaseGenerator { } // Initialize an existing object with other data, to avoid an allocation. - void InitializeExisting(const StructDef &struct_def, - std::string *code_ptr) { + void InitializeExisting(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -172,8 +142,7 @@ class PythonGenerator : public BaseGenerator { // Get the value of a struct's scalar. void GetScalarFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); GenReceiver(struct_def, code_ptr); @@ -184,8 +153,7 @@ class PythonGenerator : public BaseGenerator { } // Get the value of a table's scalar. - void GetScalarFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetScalarFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; std::string getter = GenGetter(field.value.type); @@ -195,9 +163,7 @@ class PythonGenerator : public BaseGenerator { code += OffsetPrefix(field); getter += "o + self._tab.Pos)"; auto is_bool = IsBool(field.value.type.base_type); - if (is_bool) { - getter = "bool(" + getter + ")"; - } + if (is_bool) { getter = "bool(" + getter + ")"; } code += Indent + Indent + Indent + "return " + getter + "\n"; std::string default_value; if (is_bool) { @@ -213,8 +179,7 @@ class PythonGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Struct. void GetStructFieldOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); code += MakeCamel(NormalizedName(field)); @@ -250,8 +215,7 @@ class PythonGenerator : public BaseGenerator { // Get a struct by initializing an existing struct. // Specific to Table. - void GetStructFieldOfTable(const StructDef &struct_def, - const FieldDef &field, + void GetStructFieldOfTable(const StructDef &struct_def, const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; GenReceiver(struct_def, code_ptr); @@ -296,7 +260,8 @@ class PythonGenerator : public BaseGenerator { // TODO(rw): this works and is not the good way to it: bool is_native_table = TypeName(field) == "*flatbuffers.Table"; if (is_native_table) { - code += Indent + Indent + Indent + "from flatbuffers.table import Table\n"; + code += + Indent + Indent + Indent + "from flatbuffers.table import Table\n"; } else { code += Indent + Indent + Indent; code += "from ." + TypeName(field) + " import " + TypeName(field) + "\n"; @@ -309,8 +274,7 @@ class PythonGenerator : public BaseGenerator { // Get the value of a vector's struct member. void GetMemberOfVectorOfStruct(const StructDef &struct_def, - const FieldDef &field, - std::string *code_ptr) { + const FieldDef &field, std::string *code_ptr) { std::string &code = *code_ptr; auto vectortype = field.value.type.VectorType(); @@ -388,8 +352,7 @@ class PythonGenerator : public BaseGenerator { } // Begin the creator function signature. - void BeginBuilderArgs(const StructDef &struct_def, - std::string *code_ptr) { + void BeginBuilderArgs(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "\n"; @@ -399,10 +362,10 @@ class PythonGenerator : public BaseGenerator { // Recursively generate arguments for a constructor, to deal with nested // structs. - void StructBuilderArgs(const StructDef &struct_def, - const char *nameprefix, std::string *code_ptr) { + void StructBuilderArgs(const StructDef &struct_def, const char *nameprefix, + std::string *code_ptr) { for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; const auto &field_type = field.value.type; const auto &type = @@ -439,7 +402,7 @@ class PythonGenerator : public BaseGenerator { indent + " builder.Prep(" + NumToString(struct_def.minalign) + ", "; code += NumToString(struct_def.bytesize) + ")\n"; for (auto it = struct_def.fields.vec.rbegin(); - it != struct_def.fields.vec.rend(); ++it) { + it != struct_def.fields.vec.rend(); ++it) { auto &field = **it; const auto &field_type = field.value.type; const auto &type = @@ -484,8 +447,7 @@ class PythonGenerator : public BaseGenerator { } // Get the value of a table's starting offset. - void GetStartOfTable(const StructDef &struct_def, - std::string *code_ptr) { + void GetStartOfTable(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "Start"; code += "(builder): "; @@ -495,11 +457,11 @@ class PythonGenerator : public BaseGenerator { } // Set the value of a table's field. - void BuildFieldOfTable(const StructDef &struct_def, - const FieldDef &field, const size_t offset, - std::string *code_ptr) { + void BuildFieldOfTable(const StructDef &struct_def, const FieldDef &field, + const size_t offset, std::string *code_ptr) { std::string &code = *code_ptr; - code += "def " + NormalizedName(struct_def) + "Add" + MakeCamel(NormalizedName(field)); + code += "def " + NormalizedName(struct_def) + "Add" + + MakeCamel(NormalizedName(field)); code += "(builder, "; code += MakeCamel(NormalizedName(field), false); code += "): "; @@ -521,8 +483,8 @@ class PythonGenerator : public BaseGenerator { } // Set the value of one of the members of a table's vector. - void BuildVectorOfTable(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void BuildVectorOfTable(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "Start"; code += MakeCamel(NormalizedName(field)); @@ -536,8 +498,7 @@ class PythonGenerator : public BaseGenerator { } // Get the offset of the end of a table. - void GetEndOffsetOnTable(const StructDef &struct_def, - std::string *code_ptr) { + void GetEndOffsetOnTable(const StructDef &struct_def, std::string *code_ptr) { std::string &code = *code_ptr; code += "def " + NormalizedName(struct_def) + "End"; code += "(builder): "; @@ -552,8 +513,8 @@ class PythonGenerator : public BaseGenerator { } // Generate a struct field, conditioned on its child type(s). - void GenStructAccessor(const StructDef &struct_def, - const FieldDef &field, std::string *code_ptr) { + void GenStructAccessor(const StructDef &struct_def, const FieldDef &field, + std::string *code_ptr) { GenComment(field.doc_comment, code_ptr, &def_comment, Indent.c_str()); if (IsScalar(field.value.type.base_type)) { if (struct_def.fixed) { @@ -572,7 +533,9 @@ class PythonGenerator : public BaseGenerator { GetStructFieldOfTable(struct_def, field, code_ptr); } break; - case BASE_TYPE_STRING: GetStringField(struct_def, field, code_ptr); break; + case BASE_TYPE_STRING: + GetStringField(struct_def, field, code_ptr); + break; case BASE_TYPE_VECTOR: { auto vectortype = field.value.type.VectorType(); if (vectortype.base_type == BASE_TYPE_STRUCT) { @@ -593,12 +556,11 @@ class PythonGenerator : public BaseGenerator { } // Generate table constructors, conditioned on its members' types. - void GenTableBuilders(const StructDef &struct_def, - std::string *code_ptr) { + void GenTableBuilders(const StructDef &struct_def, std::string *code_ptr) { GetStartOfTable(struct_def, code_ptr); for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; @@ -635,7 +597,7 @@ class PythonGenerator : public BaseGenerator { code += "\", size_prefixed=size_prefixed)\n"; code += "\n"; } - + // Generate struct or table methods. void GenStruct(const StructDef &struct_def, std::string *code_ptr) { if (struct_def.generated) return; @@ -646,7 +608,7 @@ class PythonGenerator : public BaseGenerator { // Generate a special accessor for the table that has been declared as // the root type. NewRootTypeFromBuffer(struct_def, code_ptr); - if (parser_.file_identifier_.length()){ + if (parser_.file_identifier_.length()) { // Generate a special function to test file_identifier GenHasFileIdentifier(struct_def, code_ptr); } @@ -655,7 +617,7 @@ class PythonGenerator : public BaseGenerator { // accessor object. This is to allow object reuse. InitializeExisting(struct_def, code_ptr); for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { auto &field = **it; if (field.deprecated) continue; @@ -693,7 +655,7 @@ class PythonGenerator : public BaseGenerator { case BASE_TYPE_VECTOR: return GenGetter(type.VectorType()); default: return "self._tab.Get(flatbuffers.number_types." + - MakeCamel(GenTypeGet(type)) + "Flags, "; + MakeCamel(GenTypeGet(type)) + "Flags, "; } } @@ -738,8 +700,7 @@ class PythonGenerator : public BaseGenerator { } // Create a struct with a builder and the struct's arguments. - void GenStructBuilder(const StructDef &struct_def, - std::string *code_ptr) { + void GenStructBuilder(const StructDef &struct_def, std::string *code_ptr) { BeginBuilderArgs(struct_def, code_ptr); StructBuilderArgs(struct_def, "", code_ptr); EndBuilderArgs(code_ptr); @@ -807,6 +768,7 @@ class PythonGenerator : public BaseGenerator { NamespaceDir(*def.defined_namespace) + NormalizedName(def) + ".py"; return SaveFile(filename.c_str(), code, false); } + private: std::unordered_set<std::string> keywords_; const SimpleFloatConstantGenerator float_const_gen_; diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index 936ac836..3c23f2f9 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -40,9 +40,7 @@ std::string MakeSnakeCase(const std::string &in) { } else if (!islower(in[i])) { // Prevent duplicate underscores for Upper_Snake_Case strings // and UPPERCASE strings. - if (islower(in[i - 1])) { - s += '_'; - } + if (islower(in[i - 1])) { s += '_'; } s += static_cast<char>(tolower(in[i])); } else { s += in[i]; @@ -200,77 +198,19 @@ class RustGenerator : public BaseGenerator { // changes to that webpage in the future. // currently-used keywords - "as", - "break", - "const", - "continue", - "crate", - "else", - "enum", - "extern", - "false", - "fn", - "for", - "if", - "impl", - "in", - "let", - "loop", - "match", - "mod", - "move", - "mut", - "pub", - "ref", - "return", - "Self", - "self", - "static", - "struct", - "super", - "trait", - "true", - "type", - "unsafe", - "use", - "where", - "while", + "as", "break", "const", "continue", "crate", "else", "enum", "extern", + "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", + "move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct", + "super", "trait", "true", "type", "unsafe", "use", "where", "while", // future possible keywords - "abstract", - "alignof", - "become", - "box", - "do", - "final", - "macro", - "offsetof", - "override", - "priv", - "proc", - "pure", - "sizeof", - "typeof", - "unsized", - "virtual", - "yield", + "abstract", "alignof", "become", "box", "do", "final", "macro", + "offsetof", "override", "priv", "proc", "pure", "sizeof", "typeof", + "unsized", "virtual", "yield", // other rust terms we should not use - "std", - "usize", - "isize", - "u8", - "i8", - "u16", - "i16", - "u32", - "i32", - "u64", - "i64", - "u128", - "i128", - "f32", - "f64", + "std", "usize", "isize", "u8", "i8", "u16", "i16", "u32", "i32", "u64", + "i64", "u128", "i128", "f32", "f64", // These are terms the code generator can implement on types. // @@ -281,13 +221,9 @@ class RustGenerator : public BaseGenerator { // implementation detail, and how we implement methods could change in // the future. as a result, we proactively block these out as reserved // words. - "follow", - "push", - "size", - "alignment", - "to_little_endian", - "from_little_endian", - nullptr }; + "follow", "push", "size", "alignment", "to_little_endian", + "from_little_endian", nullptr + }; for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw); } @@ -310,8 +246,7 @@ class RustGenerator : public BaseGenerator { // TODO(rw): Use a set data structure to reduce namespace evaluations from // O(n**2) to O(n). for (auto ns_it = parser_.namespaces_.begin(); - ns_it != parser_.namespaces_.end(); - ++ns_it) { + ns_it != parser_.namespaces_.end(); ++ns_it) { const auto &ns = *ns_it; // Generate code for all the enum declarations. @@ -381,8 +316,12 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: - case ftUnionValue: { return false; } - default: { return true; } + case ftUnionValue: { + return false; + } + default: { + return true; + } } } @@ -393,13 +332,9 @@ class RustGenerator : public BaseGenerator { for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; - if (field.deprecated) { - continue; - } + if (field.deprecated) { continue; } - if (TableBuilderTypeNeedsLifetime(field.value.type)) { - return true; - } + if (TableBuilderTypeNeedsLifetime(field.value.type)) { return true; } } return false; @@ -410,14 +345,18 @@ class RustGenerator : public BaseGenerator { bool StructMemberAccessNeedsCopy(const Type &type) const { switch (GetFullType(type)) { case ftInteger: // requires endian swap - case ftFloat: // requires endian swap - case ftBool: // no endian-swap, but do the copy for UX consistency - case ftEnumKey: { return true; } // requires endian swap - case ftStruct: { return false; } // no endian swap + case ftFloat: // requires endian swap + case ftBool: // no endian-swap, but do the copy for UX consistency + case ftEnumKey: { + return true; + } // requires endian swap + case ftStruct: { + return false; + } // no endian swap default: { // logic error: no other types can be struct members. FLATBUFFERS_ASSERT(false && "invalid struct member type"); - return false; // only to satisfy compiler's return analysis + return false; // only to satisfy compiler's return analysis } } } @@ -477,7 +416,7 @@ class RustGenerator : public BaseGenerator { auto s = src->components.begin(); auto d = dst->components.begin(); - for(;;) { + for (;;) { if (s == src->components.end()) { break; } if (d == dst->components.end()) { break; } if (*s != *d) { break; } @@ -486,9 +425,7 @@ class RustGenerator : public BaseGenerator { ++i; } - for (; s != src->components.end(); ++s) { - stream << "super::"; - } + for (; s != src->components.end(); ++s) { stream << "super::"; } for (; d != dst->components.end(); ++d) { stream << MakeSnakeCase(*d) + "::"; } @@ -509,8 +446,12 @@ class RustGenerator : public BaseGenerator { case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: { break; } - default: { FLATBUFFERS_ASSERT(false && "incorrect type given");} + case ftUnionKey: { + break; + } + default: { + FLATBUFFERS_ASSERT(false && "incorrect type given"); + } } // clang-format off @@ -560,13 +501,17 @@ class RustGenerator : public BaseGenerator { case ftBool: case ftEnumKey: case ftUnionKey: { - return GetTypeBasic(type); } + return GetTypeBasic(type); + } case ftTable: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name) + "<'a>"; } + type.struct_def->name) + + "<'a>"; + } default: { return WrapInNameSpace(type.struct_def->defined_namespace, - type.struct_def->name); } + type.struct_def->name); + } } } @@ -586,7 +531,8 @@ class RustGenerator : public BaseGenerator { GenComment(enum_def.doc_comment); code_ += "#[allow(non_camel_case_types)]"; code_ += "#[repr({{BASE_TYPE}})]"; - code_ += "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; + code_ += + "#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]"; code_ += "pub enum " + Name(enum_def) + " {"; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { @@ -644,8 +590,9 @@ class RustGenerator : public BaseGenerator { code_ += " type Output = {{ENUM_NAME}};"; code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; - code_ += " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" - "(dst, *self);"; + code_ += + " flatbuffers::emplace_scalar::<{{ENUM_NAME}}>" + "(dst, *self);"; code_ += " }"; code_ += "}"; code_ += ""; @@ -654,7 +601,7 @@ class RustGenerator : public BaseGenerator { auto num_fields = NumToString(enum_def.size()); code_ += "#[allow(non_camel_case_types)]"; code_ += "const ENUM_VALUES_{{ENUM_NAME_CAPS}}:[{{ENUM_NAME}}; " + - num_fields + "] = ["; + num_fields + "] = ["; for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { const auto &ev = **it; auto value = GetEnumValUse(enum_def, ev); @@ -727,8 +674,12 @@ class RustGenerator : public BaseGenerator { std::string GetDefaultScalarValue(const FieldDef &field) { switch (GetFullType(field.value.type)) { - case ftInteger: { return GetDefaultConstant(field); } - case ftFloat: { return GetDefaultConstant(field); } + case ftInteger: { + return GetDefaultConstant(field); + } + case ftFloat: { + return GetDefaultConstant(field); + } case ftBool: { return field.value.constant == "0" ? "false" : "true"; } @@ -742,7 +693,9 @@ class RustGenerator : public BaseGenerator { // All pointer-ish types have a default value of None, because they are // wrapped in Option. - default: { return "None"; } + default: { + return "None"; + } } } @@ -759,7 +712,7 @@ class RustGenerator : public BaseGenerator { // 3) return a hardcoded value because the vtable field value is set to zero. std::string TableBuilderArgsDefnType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(type)) { case ftInteger: @@ -774,7 +727,7 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + \ + return "Option<flatbuffers::WIPOffset<" + typname + "<" + lifetime + ">>>"; } case ftString: { @@ -792,43 +745,43 @@ class RustGenerator : public BaseGenerator { case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfBool: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", bool>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", bool>>>"; } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", " + typname + ">>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", " + typname + ">>>"; } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>>"; } case ftVectorOfString: { - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + \ - " str>>>>"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>>"; } case ftVectorOfUnionValue: { - const auto typname = WrapInNameSpace(*type.enum_def) + \ - "UnionTableOffset"; - return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + \ - lifetime + ", flatbuffers::ForwardsUOffset<" - "flatbuffers::Table<" + lifetime + ">>>>"; + const auto typname = + WrapInNameSpace(*type.enum_def) + "UnionTableOffset"; + return "Option<flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + "flatbuffers::Table<" + + lifetime + ">>>>"; } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsDefaultValue(const FieldDef &field) { @@ -839,53 +792,56 @@ class RustGenerator : public BaseGenerator { switch (GetFullType(field.value.type)) { case ftUnionKey: case ftEnumKey: { - const std::string basetype = GetTypeBasic(field.value.type); //<- never used + const std::string basetype = + GetTypeBasic(field.value.type); //<- never used return GetDefaultScalarValue(field); } - default: { return GetDefaultScalarValue(field); } + default: { + return GetDefaultScalarValue(field); + } } } std::string TableBuilderArgsAddFuncType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + typname + "<" + lifetime + + ">>>>"; } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfBool: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", bool>>"; } case ftVectorOfString: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>>"; } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", " + typname + ">>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + ", " + + typname + ">>"; } case ftVectorOfUnionValue: { - return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + \ - ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + \ - lifetime + ">>>"; + return "flatbuffers::WIPOffset<flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<flatbuffers::Table<" + lifetime + + ">>>"; } case ftEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); @@ -919,11 +875,11 @@ class RustGenerator : public BaseGenerator { } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string TableBuilderArgsAddFuncBody(const FieldDef &field) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -947,8 +903,8 @@ class RustGenerator : public BaseGenerator { } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + \ - typname + ">>"; + return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<" + + typname + ">>"; } case ftUnionValue: @@ -964,12 +920,12 @@ class RustGenerator : public BaseGenerator { return "self.fbb_.push_slot_always::<flatbuffers::WIPOffset<_>>"; } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncReturnType(const FieldDef &field, const std::string &lifetime) { - const Type& type = field.value.type; + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -982,11 +938,13 @@ class RustGenerator : public BaseGenerator { } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " " + typname, + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired(typname + "<" + lifetime + ">", + field.required); } case ftEnumKey: case ftUnionKey: { @@ -995,55 +953,68 @@ class RustGenerator : public BaseGenerator { } case ftUnionValue: { - return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", field.required); + return WrapInOptionIfNotRequired("flatbuffers::Table<" + lifetime + ">", + field.required); } case ftString: { - return WrapInOptionIfNotRequired("&" + lifetime + " str", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " str", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); if (IsOneByte(type.VectorType().base_type)) { - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + return WrapInOptionIfNotRequired( + "&" + lifetime + " [" + typname + "]", field.required); } - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfBool: { - return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " [bool]", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", " + typname + ">", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + ", " + typname + ">", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", field.required); + return WrapInOptionIfNotRequired("&" + lifetime + " [" + typname + "]", + field.required); } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<" + \ - typname + "<" + lifetime + ">>>", field.required); + return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>", + field.required); } case ftVectorOfString: { - return WrapInOptionIfNotRequired("flatbuffers::Vector<" + lifetime + ", flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>", field.required); + return WrapInOptionIfNotRequired( + "flatbuffers::Vector<" + lifetime + + ", flatbuffers::ForwardsUOffset<&" + lifetime + " str>>", + field.required); } case ftVectorOfUnionValue: { FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported"); // TODO(rw): when we do support these, we should consider using the // Into trait to convert tables to typesafe union values. - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } std::string GenTableAccessorFuncBody(const FieldDef &field, const std::string &lifetime, const std::string &offset_prefix) { - const std::string offset_name = offset_prefix + "::" + \ - GetFieldOffsetName(field); - const Type& type = field.value.type; + const std::string offset_name = + offset_prefix + "::" + GetFieldOffsetName(field); + const Type &type = field.value.type; switch (GetFullType(field.value.type)) { case ftInteger: @@ -1051,42 +1022,51 @@ class RustGenerator : public BaseGenerator { case ftBool: { const auto typname = GetTypeBasic(type); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + \ + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + default_value + ")).unwrap()"; } case ftStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<" + typname + ">(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<" + typname + ">(" + offset_name + ", None)", + field.required); } case ftTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" + \ - typname + "<" + lifetime + ">>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + typname + "<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionValue: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Table<" + lifetime + ">>>(" + offset_name + \ - ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Table<" + + lifetime + ">>>(" + offset_name + ", None)", + field.required); } case ftUnionKey: case ftEnumKey: { - const auto underlying_typname = GetTypeBasic(type); //<- never used + const auto underlying_typname = GetTypeBasic(type); //<- never used const auto typname = WrapInNameSpace(*type.enum_def); const auto default_value = GetDefaultScalarValue(field); - return "self._tab.get::<" + typname + ">(" + offset_name + \ - ", Some(" + default_value + ")).unwrap()"; + return "self._tab.get::<" + typname + ">(" + offset_name + ", Some(" + + default_value + ")).unwrap()"; } case ftString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<&str>>(" + + offset_name + ", None)", + field.required); } case ftVectorOfInteger: case ftVectorOfFloat: { const auto typname = GetTypeBasic(type.VectorType()); - std::string s = "self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + \ - ">>>(" + offset_name + ", None)"; + std::string s = + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)"; // single-byte values are safe to slice if (IsOneByte(type.VectorType().base_type)) { s += ".map(|v| v.safe_slice())"; @@ -1094,49 +1074,60 @@ class RustGenerator : public BaseGenerator { return AddUnwrapIfRequired(s, field.required); } case ftVectorOfBool: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", bool>>>(" + \ - offset_name + ", None).map(|v| v.safe_slice())", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", bool>>>(" + offset_name + + ", None).map(|v| v.safe_slice())", + field.required); } case ftVectorOfEnumKey: { const auto typname = WrapInNameSpace(*type.enum_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + lifetime + ", " + typname + ">>>(" + \ - offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + lifetime + ", " + typname + ">>>(" + offset_name + ", None)", + field.required); } case ftVectorOfStruct: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<" + typname + ">>>(" + \ - offset_name + ", None).map(|v| v.safe_slice() )", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<" + + typname + ">>>(" + offset_name + + ", None).map(|v| v.safe_slice() )", + field.required); } case ftVectorOfTable: { const auto typname = WrapInNameSpace(*type.struct_def); - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + typname + \ - "<" + lifetime + ">>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<" + + typname + "<" + lifetime + ">>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfString: { - return AddUnwrapIfRequired("self._tab.get::<flatbuffers::ForwardsUOffset<" - "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + \ - lifetime + " str>>>>(" + offset_name + ", None)", field.required); + return AddUnwrapIfRequired( + "self._tab.get::<flatbuffers::ForwardsUOffset<" + "flatbuffers::Vector<flatbuffers::ForwardsUOffset<&" + + lifetime + " str>>>>(" + offset_name + ", None)", + field.required); } case ftVectorOfUnionValue: { FLATBUFFERS_ASSERT(false && "vectors of unions are not yet supported"); - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } } - return "INVALID_CODE_GENERATION"; // for return analysis + return "INVALID_CODE_GENERATION"; // for return analysis } - bool TableFieldReturnsOption(const Type& type) { + bool TableFieldReturnsOption(const Type &type) { switch (GetFullType(type)) { case ftInteger: case ftFloat: case ftBool: case ftEnumKey: - case ftUnionKey: - return false; + case ftUnionKey: return false; default: return true; } } @@ -1172,8 +1163,9 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "impl<'a> {{STRUCT_NAME}}<'a> {"; code_ += " #[inline]"; - code_ += " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " - "Self {"; + code_ += + " pub fn init_from_table(table: flatbuffers::Table<'a>) -> " + "Self {"; code_ += " {{STRUCT_NAME}} {"; code_ += " _tab: table,"; code_ += " }"; @@ -1181,16 +1173,17 @@ class RustGenerator : public BaseGenerator { // Generate a convenient create* function that uses the above builder // to create a table in one function call. - code_.SetValue("MAYBE_US", - struct_def.fields.vec.size() == 0 ? "_" : ""); + code_.SetValue("MAYBE_US", struct_def.fields.vec.size() == 0 ? "_" : ""); code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'args>" : ""); code_ += " #[allow(unused_mut)]"; code_ += " pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr>("; - code_ += " _fbb: " - "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; - code_ += " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" - " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; + code_ += + " _fbb: " + "&'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>,"; + code_ += + " {{MAYBE_US}}args: &'args {{STRUCT_NAME}}Args{{MAYBE_LT}})" + " -> flatbuffers::WIPOffset<{{STRUCT_NAME}}<'bldr>> {"; code_ += " let mut builder = {{STRUCT_NAME}}Builder::new(_fbb);"; for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; @@ -1203,8 +1196,9 @@ class RustGenerator : public BaseGenerator { size == SizeOf(field.value.type.base_type))) { code_.SetValue("FIELD_NAME", Name(field)); if (TableFieldReturnsOption(field.value.type)) { - code_ += " if let Some(x) = args.{{FIELD_NAME}} " - "{ builder.add_{{FIELD_NAME}}(x); }"; + code_ += + " if let Some(x) = args.{{FIELD_NAME}} " + "{ builder.add_{{FIELD_NAME}}(x); }"; } else { code_ += " builder.add_{{FIELD_NAME}}(args.{{FIELD_NAME}});"; } @@ -1227,8 +1221,9 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset)); - code_ += " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " - "{{OFFSET_VALUE}};"; + code_ += + " pub const {{OFFSET_NAME}}: flatbuffers::VOffsetT = " + "{{OFFSET_VALUE}};"; } code_ += ""; } @@ -1266,9 +1261,7 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } // Generate a nested flatbuffer field, if applicable. auto nested = field.attributes.Lookup("nested_flatbuffer"); @@ -1285,14 +1278,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("OFFSET_NAME", offset_prefix + "::" + GetFieldOffsetName(field)); - code_ += " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " - " Option<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn {{FIELD_NAME}}_nested_flatbuffer(&'a self) -> " + " Option<{{STRUCT_NAME}}<'a>> {"; code_ += " match self.{{FIELD_NAME}}() {"; code_ += " None => { None }"; code_ += " Some(data) => {"; code_ += " use self::flatbuffers::Follow;"; - code_ += " Some(<flatbuffers::ForwardsUOffset" - "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; + code_ += + " Some(<flatbuffers::ForwardsUOffset" + "<{{STRUCT_NAME}}<'a>>>::follow(data, 0))"; code_ += " },"; code_ += " }"; code_ += " }"; @@ -1315,22 +1310,26 @@ class RustGenerator : public BaseGenerator { auto &ev = **u_it; if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; } - auto table_init_type = WrapInNameSpace( - ev.union_type.struct_def->defined_namespace, - ev.union_type.struct_def->name); + auto table_init_type = + WrapInNameSpace(ev.union_type.struct_def->defined_namespace, + ev.union_type.struct_def->name); - code_.SetValue("U_ELEMENT_ENUM_TYPE", - WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); + code_.SetValue( + "U_ELEMENT_ENUM_TYPE", + WrapInNameSpace(u->defined_namespace, GetEnumValUse(*u, ev))); code_.SetValue("U_ELEMENT_TABLE_TYPE", table_init_type); code_.SetValue("U_ELEMENT_NAME", MakeSnakeCase(Name(ev))); code_ += " #[inline]"; code_ += " #[allow(non_snake_case)]"; - code_ += " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " - "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; - code_ += " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; - code_ += " self.{{FIELD_NAME}}().map(|u| " - "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; + code_ += + " pub fn {{FIELD_NAME}}_as_{{U_ELEMENT_NAME}}(&self) -> " + "Option<{{U_ELEMENT_TABLE_TYPE}}<'a>> {"; + code_ += + " if self.{{FIELD_NAME}}_type() == {{U_ELEMENT_ENUM_TYPE}} {"; + code_ += + " self.{{FIELD_NAME}}().map(|u| " + "{{U_ELEMENT_TABLE_TYPE}}::init_from_table(u))"; code_ += " } else {"; code_ += " None"; code_ += " }"; @@ -1344,7 +1343,7 @@ class RustGenerator : public BaseGenerator { // Generate an args struct: code_.SetValue("MAYBE_LT", - TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); + TableBuilderArgsNeedsLifetime(struct_def) ? "<'a>" : ""); code_ += "pub struct {{STRUCT_NAME}}Args{{MAYBE_LT}} {"; for (auto it = struct_def.fields.vec.begin(); it != struct_def.fields.vec.end(); ++it) { @@ -1363,7 +1362,7 @@ class RustGenerator : public BaseGenerator { code_ += " fn default() -> Self {"; code_ += " {{STRUCT_NAME}}Args {"; for (auto it = struct_def.fields.vec.begin(); - it != struct_def.fields.vec.end(); ++it) { + it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; if (!field.deprecated) { code_.SetValue("PARAM_VALUE", TableBuilderArgsDefaultValue(field)); @@ -1379,8 +1378,9 @@ class RustGenerator : public BaseGenerator { // Generate a builder struct: code_ += "pub struct {{STRUCT_NAME}}Builder<'a: 'b, 'b> {"; code_ += " fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a>,"; - code_ += " start_: flatbuffers::WIPOffset<" - "flatbuffers::TableUnfinishedWIPOffset>,"; + code_ += + " start_: flatbuffers::WIPOffset<" + "flatbuffers::TableUnfinishedWIPOffset>,"; code_ += "}"; // Generate builder functions: @@ -1409,13 +1409,15 @@ class RustGenerator : public BaseGenerator { code_.SetValue("FIELD_TYPE", TableBuilderArgsAddFuncType(field, "'b ")); code_.SetValue("FUNC_BODY", TableBuilderArgsAddFuncBody(field)); code_ += " #[inline]"; - code_ += " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " - "{{FIELD_TYPE}}) {"; + code_ += + " pub fn add_{{FIELD_NAME}}(&mut self, {{FIELD_NAME}}: " + "{{FIELD_TYPE}}) {"; if (is_scalar) { code_.SetValue("FIELD_DEFAULT_VALUE", TableBuilderAddFuncDefaultValue(field)); - code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " - "{{FIELD_DEFAULT_VALUE}});"; + code_ += + " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}}, " + "{{FIELD_DEFAULT_VALUE}});"; } else { code_ += " {{FUNC_BODY}}({{FIELD_OFFSET}}, {{FIELD_NAME}});"; } @@ -1438,8 +1440,9 @@ class RustGenerator : public BaseGenerator { // finish() function. code_ += " #[inline]"; - code_ += " pub fn finish(self) -> " - "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; + code_ += + " pub fn finish(self) -> " + "flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>> {"; code_ += " let o = self.fbb_.end_table(self.start_);"; for (auto it = struct_def.fields.vec.begin(); @@ -1448,8 +1451,9 @@ class RustGenerator : public BaseGenerator { if (!field.deprecated && field.required) { code_.SetValue("FIELD_NAME", MakeSnakeCase(Name(field))); code_.SetValue("OFFSET_NAME", GetFieldOffsetName(field)); - code_ += " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," - "\"{{FIELD_NAME}}\");"; + code_ += + " self.fbb_.required(o, {{STRUCT_NAME}}::{{OFFSET_NAME}}," + "\"{{FIELD_NAME}}\");"; } } code_ += " flatbuffers::WIPOffset::new(o.value())"; @@ -1466,14 +1470,16 @@ class RustGenerator : public BaseGenerator { code_.SetValue("KEY_TYPE", GenTableAccessorFuncReturnType(field, "")); code_ += " #[inline]"; - code_ += " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " - " bool {"; + code_ += + " pub fn key_compare_less_than(&self, o: &{{STRUCT_NAME}}) -> " + " bool {"; code_ += " self.{{FIELD_NAME}}() < o.{{FIELD_NAME}}()"; code_ += " }"; code_ += ""; code_ += " #[inline]"; - code_ += " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " - " ::std::cmp::Ordering {"; + code_ += + " pub fn key_compare_with_value(&self, val: {{KEY_TYPE}}) -> " + " ::std::cmp::Ordering {"; code_ += " let key = self.{{FIELD_NAME}}();"; code_ += " key.cmp(&val)"; code_ += " }"; @@ -1499,10 +1505,12 @@ class RustGenerator : public BaseGenerator { code_ += ""; code_ += "#[inline]"; - code_ += "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" - "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; - code_ += " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" - "(buf)"; + code_ += + "pub fn get_size_prefixed_root_as_{{STRUCT_NAME_SNAKECASE}}" + "<'a>(buf: &'a [u8]) -> {{STRUCT_NAME}}<'a> {"; + code_ += + " flatbuffers::get_size_prefixed_root::<{{STRUCT_NAME}}<'a>>" + "(buf)"; code_ += "}"; code_ += ""; @@ -1550,13 +1558,15 @@ class RustGenerator : public BaseGenerator { code_ += "}"; code_ += ""; code_ += "#[inline]"; - code_ += "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" - "<'a, 'b>(" - "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " - "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; + code_ += + "pub fn finish_size_prefixed_{{STRUCT_NAME_SNAKECASE}}_buffer" + "<'a, 'b>(" + "fbb: &'b mut flatbuffers::FlatBufferBuilder<'a>, " + "root: flatbuffers::WIPOffset<{{STRUCT_NAME}}<'a>>) {"; if (parser_.file_identifier_.length()) { - code_ += " fbb.finish_size_prefixed(root, " - "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; + code_ += + " fbb.finish_size_prefixed(root, " + "Some({{STRUCT_NAME_CAPS}}_IDENTIFIER));"; } else { code_ += " fbb.finish_size_prefixed(root, None);"; } @@ -1577,8 +1587,8 @@ class RustGenerator : public BaseGenerator { } static void PaddingDefinition(int bits, std::string *code_ptr, int *id) { - *code_ptr += " padding" + NumToString((*id)++) + "__: u" + \ - NumToString(bits) + ","; + *code_ptr += + " padding" + NumToString((*id)++) + "__: u" + NumToString(bits) + ","; } static void PaddingInitializer(int bits, std::string *code_ptr, int *id) { @@ -1644,8 +1654,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1656,8 +1667,9 @@ class RustGenerator : public BaseGenerator { code_ += " #[inline]"; code_ += " fn push(&self, dst: &mut [u8], _rest: &[u8]) {"; code_ += " let src = unsafe {"; - code_ += " ::std::slice::from_raw_parts(" - "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; + code_ += + " ::std::slice::from_raw_parts(" + "*self as *const {{STRUCT_NAME}} as *const u8, Self::size())"; code_ += " };"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; @@ -1674,14 +1686,12 @@ class RustGenerator : public BaseGenerator { it != struct_def.fields.vec.end(); ++it) { const auto &field = **it; const auto member_name = Name(field) + "_"; - const auto reference = StructMemberAccessNeedsCopy(field.value.type) - ? "" : "&'a "; + const auto reference = + StructMemberAccessNeedsCopy(field.value.type) ? "" : "&'a "; const auto arg_name = "_" + Name(field); const auto arg_type = reference + GetTypeGet(field.value.type); - if (it != struct_def.fields.vec.begin()) { - arg_list += ", "; - } + if (it != struct_def.fields.vec.begin()) { arg_list += ", "; } arg_list += arg_name + ": "; arg_list += arg_type; init_list += " " + member_name; @@ -1717,8 +1727,9 @@ class RustGenerator : public BaseGenerator { auto field_type = TableBuilderArgsAddFuncType(field, "'a"); auto member = "self." + Name(field) + "_"; - auto value = StructMemberAccessNeedsCopy(field.value.type) ? - member + ".from_little_endian()" : member; + auto value = StructMemberAccessNeedsCopy(field.value.type) + ? member + ".from_little_endian()" + : member; code_.SetValue("FIELD_NAME", Name(field)); code_.SetValue("FIELD_TYPE", field_type); @@ -1731,22 +1742,20 @@ class RustGenerator : public BaseGenerator { code_ += " }"; // Generate a comparison function for this field if it is a key. - if (field.key) { - GenKeyFieldMethods(field); - } + if (field.key) { GenKeyFieldMethods(field); } } code_ += "}"; code_ += ""; } void GenNamespaceImports(const int white_spaces) { - std::string indent = std::string(white_spaces, ' '); - code_ += ""; - code_ += indent + "use std::mem;"; - code_ += indent + "use std::cmp::Ordering;"; - code_ += ""; - code_ += indent + "extern crate flatbuffers;"; - code_ += indent + "use self::flatbuffers::EndianScalar;"; + std::string indent = std::string(white_spaces, ' '); + code_ += ""; + code_ += indent + "use std::mem;"; + code_ += indent + "use std::cmp::Ordering;"; + code_ += ""; + code_ += indent + "extern crate flatbuffers;"; + code_ += indent + "use self::flatbuffers::EndianScalar;"; } // Set up the correct namespace. This opens a namespace if the current diff --git a/src/idl_gen_text.cpp b/src/idl_gen_text.cpp index 66926a60..1d0a3caa 100644 --- a/src/idl_gen_text.cpp +++ b/src/idl_gen_text.cpp @@ -142,8 +142,8 @@ bool Print<const void *>(const void *val, Type type, int indent, FLATBUFFERS_ASSERT(prev_val); auto union_type_byte = *prev_val; // Always a uint8_t. if (vector_index >= 0) { - auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(prev_val + - ReadScalar<uoffset_t>(prev_val)); + auto type_vec = reinterpret_cast<const Vector<uint8_t> *>( + prev_val + ReadScalar<uoffset_t>(prev_val)); union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index)); } auto enum_val = type.enum_def->ReverseLookup(union_type_byte, true); @@ -205,9 +205,7 @@ bool Print<const void *>(const void *val, Type type, int indent, // clang-format on return true; } - default: - FLATBUFFERS_ASSERT(0); - return false; + default: FLATBUFFERS_ASSERT(0); return false; } } @@ -287,7 +285,7 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, text += ":"; text += " "; switch (fd.value.type.base_type) { - // clang-format off + // clang-format off #define FLATBUFFERS_TD(ENUM, IDLTYPE, \ CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \ case BASE_TYPE_ ## ENUM: \ @@ -310,7 +308,7 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, return false; } break; - // clang-format on + // clang-format on } // Track prev val for use with union types. if (struct_def.fixed) { @@ -330,15 +328,11 @@ static bool GenStruct(const StructDef &struct_def, const Table *table, bool GenerateTextFromTable(const Parser &parser, const void *table, const std::string &table_name, std::string *_text) { auto struct_def = parser.LookupStruct(table_name); - if (struct_def == nullptr) { - return false; - } + if (struct_def == nullptr) { return false; } auto &text = *_text; text.reserve(1024); // Reduce amount of inevitable reallocs. auto root = static_cast<const Table *>(table); - if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) { - return false; - } + if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) { return false; } text += NewLine(parser.opts); return true; } @@ -348,9 +342,9 @@ bool GenerateText(const Parser &parser, const void *flatbuffer, std::string *_text) { std::string &text = *_text; FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType() - text.reserve(1024); // Reduce amount of inevitable reallocs. - auto root = parser.opts.size_prefixed ? - GetSizePrefixedRoot<Table>(flatbuffer) : GetRoot<Table>(flatbuffer); + text.reserve(1024); // Reduce amount of inevitable reallocs. + auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer) + : GetRoot<Table>(flatbuffer); if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) { return false; } diff --git a/src/idl_parser.cpp b/src/idl_parser.cpp index 37692f98..56b1547c 100644 --- a/src/idl_parser.cpp +++ b/src/idl_parser.cpp @@ -15,12 +15,11 @@ */ #include <algorithm> +#include <cmath> #include <list> #include <string> #include <utility> -#include <cmath> - #include "flatbuffers/idl.h" #include "flatbuffers/util.h" @@ -114,8 +113,8 @@ std::string MakeScreamingCamel(const std::string &in) { return s; } -void DeserializeDoc( std::vector<std::string> &doc, - const Vector<Offset<String>> *documentation) { +void DeserializeDoc(std::vector<std::string> &doc, + const Vector<Offset<String>> *documentation) { if (documentation == nullptr) return; for (uoffset_t index = 0; index < documentation->size(); index++) doc.push_back(documentation->Get(index)->str()); @@ -399,7 +398,8 @@ CheckedError Parser::Next() { "illegal Unicode sequence (unpaired high surrogate)"); } // reset if non-printable - attr_is_trivial_ascii_string_ &= check_ascii_range(*cursor_, ' ', '~'); + attr_is_trivial_ascii_string_ &= + check_ascii_range(*cursor_, ' ', '~'); attribute_ += *cursor_++; } @@ -437,7 +437,7 @@ CheckedError Parser::Next() { cursor_ += 2; break; } - FLATBUFFERS_FALLTHROUGH(); // else fall thru + FLATBUFFERS_FALLTHROUGH(); // else fall thru default: const auto has_sign = (c == '+') || (c == '-'); // '-'/'+' and following identifier - can be a predefined constant like: @@ -451,14 +451,15 @@ CheckedError Parser::Next() { return NoError(); } - auto dot_lvl = (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen - if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum? + auto dot_lvl = + (c == '.') ? 0 : 1; // dot_lvl==0 <=> exactly one '.' seen + if (!dot_lvl && !is_digit(*cursor_)) return NoError(); // enum? // Parser accepts hexadecimal-floating-literal (see C++ 5.13.4). if (is_digit(c) || has_sign || !dot_lvl) { const auto start = cursor_ - 1; auto start_digits = !is_digit(c) ? cursor_ : cursor_ - 1; - if (!is_digit(c) && is_digit(*cursor_)){ - start_digits = cursor_; // see digit in cursor_ position + if (!is_digit(c) && is_digit(*cursor_)) { + start_digits = cursor_; // see digit in cursor_ position c = *cursor_++; } // hex-float can't begind with '.' @@ -501,7 +502,8 @@ CheckedError Parser::Next() { } std::string ch; ch = c; - if (false == check_ascii_range(c, ' ', '~')) ch = "code: " + NumToString(c); + if (false == check_ascii_range(c, ' ', '~')) + ch = "code: " + NumToString(c); return Error("illegal character: " + ch); } } @@ -730,7 +732,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (!IsScalar(type.base_type) || (struct_def.fixed && field->value.constant != "0")) return Error( - "default values currently only supported for scalars in tables"); + "default values currently only supported for scalars in tables"); } // Append .0 if the value has not it (skip hex and scientific floats). // This suffix needed for generated C++ code. @@ -738,7 +740,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { auto &text = field->value.constant; FLATBUFFERS_ASSERT(false == text.empty()); auto s = text.c_str(); - while(*s == ' ') s++; + while (*s == ' ') s++; if (*s == '-' || *s == '+') s++; // 1) A float constants (nan, inf, pi, etc) is a kind of identifier. // 2) A float number needn't ".0" at the end if it has exponent. @@ -774,7 +776,8 @@ CheckedError Parser::ParseField(StructDef &struct_def) { field->deprecated = field->attributes.Lookup("deprecated") != nullptr; auto hash_name = field->attributes.Lookup("hash"); if (hash_name) { - switch ((type.base_type == BASE_TYPE_VECTOR) ? type.element : type.base_type) { + switch ((type.base_type == BASE_TYPE_VECTOR) ? type.element + : type.base_type) { case BASE_TYPE_SHORT: case BASE_TYPE_USHORT: { if (FindHashFunction16(hash_name->constant.c_str()) == nullptr) @@ -798,7 +801,8 @@ CheckedError Parser::ParseField(StructDef &struct_def) { } default: return Error( - "only short, ushort, int, uint, long and ulong data types support hashing."); + "only short, ushort, int, uint, long and ulong data types support " + "hashing."); } } auto cpp_type = field->attributes.Lookup("cpp_type"); @@ -817,8 +821,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (field->deprecated && struct_def.fixed) return Error("can't deprecate fields in a struct"); field->required = field->attributes.Lookup("required") != nullptr; - if (field->required && - (struct_def.fixed || IsScalar(type.base_type))) + if (field->required && (struct_def.fixed || IsScalar(type.base_type))) return Error("only non-scalar fields in tables may be 'required'"); field->key = field->attributes.Lookup("key") != nullptr; if (field->key) { @@ -861,8 +864,7 @@ CheckedError Parser::ParseField(StructDef &struct_def) { if (field->attributes.Lookup("flexbuffer")) { field->flexbuffer = true; uses_flexbuffers_ = true; - if (type.base_type != BASE_TYPE_VECTOR || - type.element != BASE_TYPE_UCHAR) + if (type.base_type != BASE_TYPE_VECTOR || type.element != BASE_TYPE_UCHAR) return Error("flexbuffer attribute may only apply to a vector of ubyte"); } @@ -902,8 +904,7 @@ CheckedError Parser::ParseComma() { CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, size_t parent_fieldn, const StructDef *parent_struct_def, - uoffset_t count, - bool inside_vector) { + uoffset_t count, bool inside_vector) { switch (val.type.base_type) { case BASE_TYPE_UNION: { FLATBUFFERS_ASSERT(field); @@ -921,8 +922,8 @@ CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, uoffset_t offset; ECHECK(atot(elem->first.constant.c_str(), *this, &offset)); vector_of_union_types = reinterpret_cast<Vector<uint8_t> *>( - builder_.GetCurrentBufferPointer() + - builder_.GetSize() - offset); + builder_.GetCurrentBufferPointer() + builder_.GetSize() - + offset); break; } } else { @@ -964,8 +965,7 @@ CheckedError Parser::ParseAnyValue(Value &val, FieldDef *field, } } if (constant.empty() && !vector_of_union_types) { - return Error("missing type field for this union value: " + - field->name); + return Error("missing type field for this union value: " + field->name); } uint8_t enum_idx; if (vector_of_union_types) { @@ -1040,10 +1040,9 @@ void Parser::SerializeStruct(FlatBufferBuilder &builder, builder.AddStructOffset(val.offset, builder.GetSize()); } -template <typename F> +template<typename F> CheckedError Parser::ParseTableDelimiters(size_t &fieldn, - const StructDef *struct_def, - F body) { + const StructDef *struct_def, F body) { // We allow tables both as JSON object{ .. } with field names // or vector[..] with all fields in order char terminator = '}'; @@ -1217,7 +1216,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value, reinterpret_cast<const uint8_t*>(field_value.constant.c_str()), InlineSize(field_value.type)); break; - // clang-format on + // clang-format on } } } @@ -1243,7 +1242,7 @@ CheckedError Parser::ParseTable(const StructDef &struct_def, std::string *value, return NoError(); } -template <typename F> +template<typename F> CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) { EXPECT('['); for (;;) { @@ -1259,12 +1258,11 @@ CheckedError Parser::ParseVectorDelimiters(uoffset_t &count, F body) { static bool CompareType(const uint8_t *a, const uint8_t *b, BaseType ftype) { switch (ftype) { - #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, \ - PTYPE, RTYPE, KTYPE) \ - case BASE_TYPE_ ## ENUM: \ - return ReadScalar<CTYPE>(a) < ReadScalar<CTYPE>(b); +#define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, \ + RTYPE, KTYPE) \ + case BASE_TYPE_##ENUM: return ReadScalar<CTYPE>(a) < ReadScalar<CTYPE>(b); FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD) - #undef FLATBUFFERS_TD +#undef FLATBUFFERS_TD case BASE_TYPE_STRING: // Indirect offset pointer to string pointer. a += ReadScalar<uoffset_t>(a); @@ -1278,21 +1276,21 @@ static bool CompareType(const uint8_t *a, const uint8_t *b, BaseType ftype) { // See below for why we need our own sort :( template<typename T, typename F, typename S> void SimpleQsort(T *begin, T *end, size_t width, F comparator, S swapper) { - if (end - begin <= static_cast<ptrdiff_t>(width)) return; - auto l = begin + width; - auto r = end; - while (l < r) { - if (comparator(begin, l)) { - r -= width; - swapper(l, r); - } else { - l++; - } + if (end - begin <= static_cast<ptrdiff_t>(width)) return; + auto l = begin + width; + auto r = end; + while (l < r) { + if (comparator(begin, l)) { + r -= width; + swapper(l, r); + } else { + l++; } - l -= width; - swapper(begin, l); - SimpleQsort(begin, l, width, comparator, swapper); - SimpleQsort(r, end, width, comparator, swapper); + } + l -= width; + swapper(begin, l); + SimpleQsort(begin, l, width, comparator, swapper); + SimpleQsort(r, end, width, comparator, swapper); } CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue, @@ -1359,46 +1357,49 @@ CheckedError Parser::ParseVector(const Type &type, uoffset_t *ovalue, static BaseType ftype = key->value.type.base_type; if (type.struct_def->fixed) { - auto v = reinterpret_cast<VectorOfAny *>( - builder_.GetCurrentBufferPointer()); - SimpleQsort<uint8_t>(v->Data(), - v->Data() + v->size() * type.struct_def->bytesize, - type.struct_def->bytesize, - [](const uint8_t *a, const uint8_t *b) -> bool { - return CompareType(a + offset, b + offset, ftype); - }, [&](uint8_t *a, uint8_t *b) { - // FIXME: faster? - for (size_t i = 0; i < type.struct_def->bytesize; i++) { - std::swap(a[i], b[i]); - } - }); + auto v = + reinterpret_cast<VectorOfAny *>(builder_.GetCurrentBufferPointer()); + SimpleQsort<uint8_t>( + v->Data(), v->Data() + v->size() * type.struct_def->bytesize, + type.struct_def->bytesize, + [](const uint8_t *a, const uint8_t *b) -> bool { + return CompareType(a + offset, b + offset, ftype); + }, + [&](uint8_t *a, uint8_t *b) { + // FIXME: faster? + for (size_t i = 0; i < type.struct_def->bytesize; i++) { + std::swap(a[i], b[i]); + } + }); } else { auto v = reinterpret_cast<Vector<Offset<Table>> *>( - builder_.GetCurrentBufferPointer()); + builder_.GetCurrentBufferPointer()); // Here also can't use std::sort. We do have an iterator type for it, // but it is non-standard as it will dereference the offsets, and thus // can't be used to swap elements. - SimpleQsort<Offset<Table>>(v->data(), v->data() + v->size(), 1, - [](const Offset<Table> *_a, const Offset<Table> *_b) -> bool { - // Indirect offset pointer to table pointer. - auto a = reinterpret_cast<const uint8_t *>(_a) + - ReadScalar<uoffset_t>(_a); - auto b = reinterpret_cast<const uint8_t *>(_b) + - ReadScalar<uoffset_t>(_b); - // Fetch field address from table. - a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset); - b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset); - return CompareType(a, b, ftype); - }, [&](Offset<Table> *a, Offset<Table> *b) { - // These are serialized offsets, so are relative where they are - // stored in memory, so compute the distance between these pointers: - ptrdiff_t diff = (b - a) * sizeof(Offset<Table>); - assert(diff >= 0); // Guaranteed by SimpleQsort. - auto udiff = static_cast<uoffset_t>(diff); - a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff); - b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff); - std::swap(*a, *b); - }); + SimpleQsort<Offset<Table>>( + v->data(), v->data() + v->size(), 1, + [](const Offset<Table> *_a, const Offset<Table> *_b) -> bool { + // Indirect offset pointer to table pointer. + auto a = reinterpret_cast<const uint8_t *>(_a) + + ReadScalar<uoffset_t>(_a); + auto b = reinterpret_cast<const uint8_t *>(_b) + + ReadScalar<uoffset_t>(_b); + // Fetch field address from table. + a = reinterpret_cast<const Table *>(a)->GetAddressOf(offset); + b = reinterpret_cast<const Table *>(b)->GetAddressOf(offset); + return CompareType(a, b, ftype); + }, + [&](Offset<Table> *a, Offset<Table> *b) { + // These are serialized offsets, so are relative where they are + // stored in memory, so compute the distance between these pointers: + ptrdiff_t diff = (b - a) * sizeof(Offset<Table>); + assert(diff >= 0); // Guaranteed by SimpleQsort. + auto udiff = static_cast<uoffset_t>(diff); + a->o = EndianScalar(ReadScalar<uoffset_t>(a) - udiff); + b->o = EndianScalar(ReadScalar<uoffset_t>(b) + udiff); + std::swap(*a, *b); + }); } } return NoError(); @@ -1478,12 +1479,11 @@ CheckedError Parser::ParseNestedFlatbuffer(Value &val, FieldDef *field, nested_parser.enums_.dict.clear(); nested_parser.enums_.vec.clear(); - if (!ok) { - ECHECK(Error(nested_parser.error_)); - } + if (!ok) { ECHECK(Error(nested_parser.error_)); } // Force alignment for nested flatbuffer - builder_.ForceVectorAlignment(nested_parser.builder_.GetSize(), sizeof(uint8_t), - nested_parser.builder_.GetBufferMinAlignment()); + builder_.ForceVectorAlignment( + nested_parser.builder_.GetSize(), sizeof(uint8_t), + nested_parser.builder_.GetBufferMinAlignment()); auto off = builder_.CreateVector(nested_parser.builder_.GetBufferPointer(), nested_parser.builder_.GetSize()); @@ -1499,7 +1499,7 @@ CheckedError Parser::ParseMetaData(SymbolTable<Value> *attributes) { auto name = attribute_; if (false == (Is(kTokenIdentifier) || Is(kTokenStringConstant))) return Error("attribute name must be either identifier or string: " + - name); + name); if (known_attributes_.find(name) == known_attributes_.end()) return Error("user define attributes must be declared before use: " + name); @@ -1648,10 +1648,10 @@ template<typename T> inline void SingleValueRepack(Value &e, T val) { } #if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) // Normilaze defaults NaN to unsigned quiet-NaN(0). -static inline void SingleValueRepack(Value& e, float val) { +static inline void SingleValueRepack(Value &e, float val) { if (val != val) e.constant = "nan"; } -static inline void SingleValueRepack(Value& e, double val) { +static inline void SingleValueRepack(Value &e, double val) { if (val != val) e.constant = "nan"; } #endif @@ -1774,7 +1774,7 @@ CheckedError Parser::ParseSingleValue(const std::string *name, Value &e, "' to value of <" + std::string(kTypeNames[in_type]) + "> type."; return Error(msg); } - const auto match_type = e.type.base_type; // may differ from in_type + const auto match_type = e.type.base_type; // may differ from in_type // The check_now flag must be true when parse a fbs-schema. // This flag forces to check default scalar values or metadata of field. // For JSON parser the flag should be false. @@ -2210,11 +2210,10 @@ CheckedError Parser::CheckClash(std::vector<FieldDef *> &fields, bool Parser::SupportsAdvancedUnionFeatures() const { return opts.lang_to_generate != 0 && - (opts.lang_to_generate & ~(IDLOptions::kCpp | IDLOptions::kJs | - IDLOptions::kTs | IDLOptions::kPhp | - IDLOptions::kJava | IDLOptions::kCSharp | - IDLOptions::kKotlin | - IDLOptions::kBinary)) == 0; + (opts.lang_to_generate & + ~(IDLOptions::kCpp | IDLOptions::kJs | IDLOptions::kTs | + IDLOptions::kPhp | IDLOptions::kJava | IDLOptions::kCSharp | + IDLOptions::kKotlin | IDLOptions::kBinary)) == 0; } bool Parser::SupportsAdvancedArrayFeatures() const { @@ -2486,8 +2485,8 @@ CheckedError Parser::StartEnum(const std::string &enum_name, bool is_union, if (enums_.Add(current_namespace_->GetFullyQualifiedName(enum_name), &enum_def)) return Error("enum already exists: " + enum_name); - enum_def.underlying_type.base_type = is_union ? BASE_TYPE_UTYPE - : BASE_TYPE_INT; + enum_def.underlying_type.base_type = + is_union ? BASE_TYPE_UTYPE : BASE_TYPE_INT; enum_def.underlying_type.enum_def = &enum_def; if (dest) *dest = &enum_def; return NoError(); @@ -2623,8 +2622,8 @@ CheckedError Parser::ParseProtoFields(StructDef *struct_def, bool isextend, if (oneof_type.base_type != BASE_TYPE_STRUCT || !oneof_type.struct_def || oneof_type.struct_def->fixed) return Error("oneof '" + name + - "' cannot be mapped to a union because member '" + - oneof_field.name + "' is not a table type."); + "' cannot be mapped to a union because member '" + + oneof_field.name + "' is not a table type."); EnumValBuilder evb(*this, *oneof_union); auto ev = evb.CreateEnumerator(oneof_type.struct_def->name); ev->union_type = oneof_type; @@ -2989,9 +2988,7 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, // entered into included_files_. // This is recursive, but only go as deep as the number of include // statements. - if (source_filename) { - included_files_.erase(source_filename); - } + if (source_filename) { included_files_.erase(source_filename); } return DoParse(source, include_paths, source_filename, include_filename); } @@ -3015,9 +3012,9 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, uoffset_t toff; ECHECK(ParseTable(*root_struct_def_, nullptr, &toff)); if (opts.size_prefixed) { - builder_.FinishSizePrefixed(Offset<Table>(toff), file_identifier_.length() - ? file_identifier_.c_str() - : nullptr); + builder_.FinishSizePrefixed( + Offset<Table>(toff), + file_identifier_.length() ? file_identifier_.c_str() : nullptr); } else { builder_.Finish(Offset<Table>(toff), file_identifier_.length() ? file_identifier_.c_str() @@ -3038,8 +3035,7 @@ CheckedError Parser::DoParse(const char *source, const char **include_paths, if (opts.root_type.empty()) { if (!SetRootType(root_type.c_str())) return Error("unknown root type: " + root_type); - if (root_struct_def_->fixed) - return Error("root type must be a table"); + if (root_struct_def_->fixed) return Error("root type must be a table"); } EXPECT(';'); } else if (IsIdent("file_identifier")) { @@ -3144,10 +3140,9 @@ void Parser::Serialize() { auto fiid__ = builder_.CreateString(file_identifier_); auto fext__ = builder_.CreateString(file_extension_); auto serv__ = builder_.CreateVectorOfSortedTables(&service_offsets); - auto schema_offset = - reflection::CreateSchema(builder_, objs__, enum__, fiid__, fext__, - (root_struct_def_ ? root_struct_def_->serialized_location : 0), - serv__); + auto schema_offset = reflection::CreateSchema( + builder_, objs__, enum__, fiid__, fext__, + (root_struct_def_ ? root_struct_def_->serialized_location : 0), serv__); if (opts.size_prefixed) { builder_.FinishSizePrefixed(schema_offset, reflection::SchemaIdentifier()); } else { @@ -3193,22 +3188,20 @@ Offset<reflection::Object> StructDef::Serialize(FlatBufferBuilder *builder, auto flds__ = builder->CreateVectorOfSortedTables(&field_offsets); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateObject(*builder, name__, flds__, fixed, static_cast<int>(minalign), - static_cast<int>(bytesize), - attr__, docs__); + static_cast<int>(bytesize), attr__, docs__); } bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) { - if (!DeserializeAttributes(parser, object->attributes())) - return false; + if (!DeserializeAttributes(parser, object->attributes())) return false; DeserializeDoc(doc_comment, object->documentation()); name = parser.UnqualifiedName(object->name()->str()); predecl = false; sortbysize = attributes.Lookup("original_order") == nullptr && !fixed; - const auto& of = *(object->fields()); + const auto &of = *(object->fields()); auto indexes = std::vector<uoffset_t>(of.size()); for (uoffset_t i = 0; i < of.size(); i++) indexes[of.Get(i)->id()] = i; size_t tmp_struct_size = 0; @@ -3224,9 +3217,7 @@ bool StructDef::Deserialize(Parser &parser, const reflection::Object *object) { // Recompute padding since that's currently not serialized. auto size = InlineSize(field_def->value.type); auto next_field = - i + 1 < indexes.size() - ? of.Get(indexes[i+1]) - : nullptr; + i + 1 < indexes.size() ? of.Get(indexes[i + 1]) : nullptr; tmp_struct_size += size; field_def->padding = next_field ? (next_field->offset() - field_def->value.offset) - size @@ -3245,9 +3236,10 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder, auto type__ = value.type.Serialize(builder); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateField(*builder, name__, type__, id, value.offset, + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateField( + *builder, name__, type__, id, value.offset, // Is uint64>max(int64) tested? IsInteger(value.type.base_type) ? StringToInt(value.constant.c_str()) : 0, // result may be platform-dependent if underlying is float (not double) @@ -3261,8 +3253,7 @@ Offset<reflection::Field> FieldDef::Serialize(FlatBufferBuilder *builder, bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) { name = field->name()->str(); defined_namespace = parser.current_namespace_; - if (!value.type.Deserialize(parser, field->type())) - return false; + if (!value.type.Deserialize(parser, field->type())) return false; value.offset = field->offset(); if (IsInteger(value.type.base_type)) { value.constant = NumToString(field->default_integer()); @@ -3276,8 +3267,7 @@ bool FieldDef::Deserialize(Parser &parser, const reflection::Field *field) { deprecated = field->deprecated(); required = field->required(); key = field->key(); - if (!DeserializeAttributes(parser, field->attributes())) - return false; + if (!DeserializeAttributes(parser, field->attributes())) return false; // TODO: this should probably be handled by a separate attribute if (attributes.Lookup("flexbuffer")) { flexbuffer = true; @@ -3301,18 +3291,16 @@ Offset<reflection::RPCCall> RPCCall::Serialize(FlatBufferBuilder *builder, auto name__ = builder->CreateString(name); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateRPCCall(*builder, name__, - request->serialized_location, - response->serialized_location, - attr__, docs__); + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateRPCCall( + *builder, name__, request->serialized_location, + response->serialized_location, attr__, docs__); } bool RPCCall::Deserialize(Parser &parser, const reflection::RPCCall *call) { name = call->name()->str(); - if (!DeserializeAttributes(parser, call->attributes())) - return false; + if (!DeserializeAttributes(parser, call->attributes())) return false; DeserializeDoc(doc_comment, call->documentation()); request = parser.structs_.Lookup(call->request()->name()->str()); response = parser.structs_.Lookup(call->response()->name()->str()); @@ -3331,8 +3319,8 @@ Offset<reflection::Service> ServiceDef::Serialize(FlatBufferBuilder *builder, auto call__ = builder->CreateVector(servicecall_offsets); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateService(*builder, name__, call__, attr__, docs__); } @@ -3349,8 +3337,7 @@ bool ServiceDef::Deserialize(Parser &parser, } } } - if (!DeserializeAttributes(parser, service->attributes())) - return false; + if (!DeserializeAttributes(parser, service->attributes())) return false; DeserializeDoc(doc_comment, service->documentation()); return true; } @@ -3367,8 +3354,8 @@ Offset<reflection::Enum> EnumDef::Serialize(FlatBufferBuilder *builder, auto type__ = underlying_type.Serialize(builder); auto attr__ = SerializeAttributes(builder, parser); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; + ? builder->CreateVectorOfStrings(doc_comment) + : 0; return reflection::CreateEnum(*builder, name__, vals__, is_union, type__, attr__, docs__); } @@ -3387,8 +3374,7 @@ bool EnumDef::Deserialize(Parser &parser, const reflection::Enum *_enum) { if (!underlying_type.Deserialize(parser, _enum->underlying_type())) { return false; } - if (!DeserializeAttributes(parser, _enum->attributes())) - return false; + if (!DeserializeAttributes(parser, _enum->attributes())) return false; DeserializeDoc(doc_comment, _enum->documentation()); return true; } @@ -3398,9 +3384,10 @@ Offset<reflection::EnumVal> EnumVal::Serialize(FlatBufferBuilder *builder, auto name__ = builder->CreateString(name); auto type__ = union_type.Serialize(builder); auto docs__ = parser.opts.binary_schema_comments - ? builder->CreateVectorOfStrings(doc_comment) - : 0; - return reflection::CreateEnumVal(*builder, name__, value, + ? builder->CreateVectorOfStrings(doc_comment) + : 0; + return reflection::CreateEnumVal( + *builder, name__, value, union_type.struct_def ? union_type.struct_def->serialized_location : 0, type__, docs__); } @@ -3409,8 +3396,7 @@ bool EnumVal::Deserialize(const Parser &parser, const reflection::EnumVal *val) { name = val->name()->str(); value = val->value(); - if (!union_type.Deserialize(parser, val->union_type())) - return false; + if (!union_type.Deserialize(parser, val->union_type())) return false; DeserializeDoc(doc_comment, val->documentation()); return true; } @@ -3432,8 +3418,7 @@ bool Type::Deserialize(const Parser &parser, const reflection::Type *type) { bool is_series = type->base_type() == reflection::Vector || type->base_type() == reflection::Array; if (type->base_type() == reflection::Obj || - (is_series && - type->element() == reflection::Obj)) { + (is_series && type->element() == reflection::Obj)) { if (static_cast<size_t>(type->index()) < parser.structs_.vec.size()) { struct_def = parser.structs_.vec[type->index()]; struct_def->refcount++; @@ -3474,8 +3459,7 @@ Definition::SerializeAttributes(FlatBufferBuilder *builder, bool Definition::DeserializeAttributes( Parser &parser, const Vector<Offset<reflection::KeyValue>> *attrs) { - if (attrs == nullptr) - return true; + if (attrs == nullptr) return true; for (uoffset_t i = 0; i < attrs->size(); ++i) { auto kv = attrs->Get(i); auto value = new Value(); @@ -3495,7 +3479,7 @@ bool Definition::DeserializeAttributes( bool Parser::Deserialize(const uint8_t *buf, const size_t size) { flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(buf), size); bool size_prefixed = false; - if(!reflection::SchemaBufferHasIdentifier(buf)) { + if (!reflection::SchemaBufferHasIdentifier(buf)) { if (!flatbuffers::BufferHasIdentifier(buf, reflection::SchemaIdentifier(), true)) return false; @@ -3504,9 +3488,7 @@ bool Parser::Deserialize(const uint8_t *buf, const size_t size) { } auto verify_fn = size_prefixed ? &reflection::VerifySizePrefixedSchemaBuffer : &reflection::VerifySchemaBuffer; - if (!verify_fn(verifier)) { - return false; - } + if (!verify_fn(verifier)) { return false; } auto schema = size_prefixed ? reflection::GetSizePrefixedSchema(buf) : reflection::GetSchema(buf); return Deserialize(schema); @@ -3555,7 +3537,7 @@ bool Parser::Deserialize(const reflection::Schema *schema) { auto struct_def = structs_.Lookup(qualified_name); struct_def->defined_namespace = GetNamespace(qualified_name, namespaces_, namespaces_index); - if (!struct_def->Deserialize(*this, * it)) { return false; } + if (!struct_def->Deserialize(*this, *it)) { return false; } if (schema->root_table() == *it) { root_struct_def_ = struct_def; } } for (auto it = schema->enums()->begin(); it != schema->enums()->end(); ++it) { diff --git a/src/reflection.cpp b/src/reflection.cpp index fc211c5f..409dbd03 100644 --- a/src/reflection.cpp +++ b/src/reflection.cpp @@ -15,6 +15,7 @@ */ #include "flatbuffers/reflection.h" + #include "flatbuffers/util.h" // Helper functionality for reflection. @@ -431,8 +432,8 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb, break; } } - FLATBUFFERS_FALLTHROUGH(); // fall thru - default: { // Scalars and structs. + FLATBUFFERS_FALLTHROUGH(); // fall thru + default: { // Scalars and structs. auto element_size = GetTypeSize(element_base_type); if (elemobjectdef && elemobjectdef->is_struct()) element_size = elemobjectdef->bytesize(); @@ -466,7 +467,7 @@ Offset<const Table *> CopyTable(FlatBufferBuilder &fbb, break; } } - FLATBUFFERS_FALLTHROUGH(); // fall thru + FLATBUFFERS_FALLTHROUGH(); // fall thru case reflection::Union: case reflection::String: case reflection::Vector: @@ -495,9 +496,8 @@ bool VerifyStruct(flatbuffers::Verifier &v, auto offset = parent_table.GetOptionalFieldOffset(field_offset); if (required && !offset) { return false; } - return !offset || - v.Verify(reinterpret_cast<const uint8_t *>(&parent_table), offset, - obj.bytesize()); + return !offset || v.Verify(reinterpret_cast<const uint8_t *>(&parent_table), + offset, obj.bytesize()); } bool VerifyVectorOfStructs(flatbuffers::Verifier &v, @@ -535,9 +535,8 @@ bool VerifyUnion(flatbuffers::Verifier &v, const reflection::Schema &schema, } case reflection::String: return v.VerifyString( - reinterpret_cast<const flatbuffers::String *>(elem)); - default: - return false; + reinterpret_cast<const flatbuffers::String *>(elem)); + default: return false; } } @@ -597,27 +596,24 @@ bool VerifyVector(flatbuffers::Verifier &v, const reflection::Schema &schema, } } case reflection::Union: { - auto vec = flatbuffers::GetFieldV<flatbuffers::Offset<uint8_t>>(table, - vec_field); + auto vec = flatbuffers::GetFieldV<flatbuffers::Offset<uint8_t>>( + table, vec_field); if (!v.VerifyVector(vec)) return false; if (!vec) return true; - auto type_vec = table.GetPointer<Vector<uint8_t> *> - (vec_field.offset() - sizeof(voffset_t)); + auto type_vec = table.GetPointer<Vector<uint8_t> *>(vec_field.offset() - + sizeof(voffset_t)); if (!v.VerifyVector(type_vec)) return false; for (uoffset_t j = 0; j < vec->size(); j++) { // get union type from the prev field auto utype = type_vec->Get(j); auto elem = vec->Get(j); - if (!VerifyUnion(v, schema, utype, elem, vec_field)) - return false; + if (!VerifyUnion(v, schema, utype, elem, vec_field)) return false; } return true; } case reflection::Vector: case reflection::None: - default: - FLATBUFFERS_ASSERT(false); - return false; + default: FLATBUFFERS_ASSERT(false); return false; } } @@ -663,8 +659,7 @@ bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema, } break; case reflection::Vector: - if (!VerifyVector(v, schema, *table, *field_def)) - return false; + if (!VerifyVector(v, schema, *table, *field_def)) return false; break; case reflection::Obj: { auto child_obj = schema.objects()->Get(field_def->type()->index()); @@ -687,15 +682,11 @@ bool VerifyObject(flatbuffers::Verifier &v, const reflection::Schema &schema, voffset_t utype_offset = field_def->offset() - sizeof(voffset_t); auto utype = table->GetField<uint8_t>(utype_offset, 0); auto uval = reinterpret_cast<const uint8_t *>( - flatbuffers::GetFieldT(*table, *field_def)); - if (!VerifyUnion(v, schema, utype, uval, *field_def)) { - return false; - } + flatbuffers::GetFieldT(*table, *field_def)); + if (!VerifyUnion(v, schema, utype, uval, *field_def)) { return false; } break; } - default: - FLATBUFFERS_ASSERT(false); - break; + default: FLATBUFFERS_ASSERT(false); break; } } diff --git a/src/util.cpp b/src/util.cpp index b80bed25..08b77918 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -242,9 +242,9 @@ bool SetGlobalTestLocale(const char *locale_name, std::string *_value) { } bool ReadEnvironmentVariable(const char *var_name, std::string *_value) { - #ifdef _MSC_VER - __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS - #endif +#ifdef _MSC_VER + __pragma(warning(disable : 4996)); // _CRT_SECURE_NO_WARNINGS +#endif auto env_str = std::getenv(var_name); if (!env_str) return false; if (_value) *_value = std::string(env_str); |