Squashed 'third_party/flatbuffers/' changes from e5f331db9..bc44fad35
bc44fad35 UnPackTo disable merge by default (#7527)
4fca4dc60 [TS/JS] Move TS tests to dedicated folder and deps upgrade (#7508)
036032373 Bump junit from 4.13 to 4.13.1 in /java (#7526)
89dfb43f3 Replace `bash JavaTest.sh` with `mvn test` (#7500)
c49aff4b6 enabled cpp17 tests in CI (#7524)
56e60223c prevent force_align attribute on enums (#7523)
89b1f5aa1 remove travis config (#7522)
b90159823 [Java][Flexbuffers] Add API to add nullables into the buffer. (#7521)
8cdc6a288 Install BuildFlatBuffers.cmake (#7519)
a67e35aff Moves all of the swift test code into tests/swift (#7509)
f124e41ae Updated Readme
4c954181c [Java][FlexBuffers] throwing exception for untyped fixed vectors (#7507)
7f7547737 [Android] Remove maven dependency of flatbuffers and use source folder (#7503)
a79d61ea8 Fixes issue with cocoapods failing to be published because of docc (#7505)
d465b39c3 [CMake]: fix breaking find_package change (#7499) (#7502)
c5a609dc2 [C#] Prepares for official Nuget release (#7496)
5634dc3d0 [ISSUE-6268] returns NaN insteadof nan (#7498)
37e37b8ca Updates cocoapods version (#7497)
8fd4534fb update android multidex setting (#7495)
d5427da52 Disable Android Build (#7494)
06c5c7ed0 FlatBuffers Version 2.0.8 (#7492)
b190ce11b Verifier Refinements (#7490)
bf5d23230 Namer applied to Typescript generator (#7488)
ce382d6dd [TS/JS] Add rollup and config to generate iife flatbuffers bundle (#7449)
41d9add7e C++: Add option to skip verifying nested flatbuffers (#7489)
6a8742754 [C++] support native_inline attribute for vector of tables (#7479)
694add668 Refactor test.cpp (#7487)
7edf8c908 Update scorecard to 1.1.2
b86387442 Fix typos (#7483)
e2eb5ee67 Include <array> head in stl_emulation.h (#7480)
994502b6d Version number in file package.json updated to 2.0.7 (#7476)
fa41e8367 [C++] Fixed crash when copying table with empty shared strings (#7477)
799cc8f7b Use type traits for specialization (#7475)
b7eb44147 Disable RTTI and rework use in idl_gen_ts.cpp (#7474)
8d01c5859 CMake project version detection made more robust (#7473)
237e8b71f Moved compiler warnings around (#7471)
eeb8fd60d Include builder.addOffset for vector of structs (#7470)
fef2ffc4d Use schema include name for keep-prefix (#7469)
8367664f1 Flatbuffers Version 2.0.7 (#7462)
d6f06c33f Reworked keep prefix (#7456)
627e8bf36 update grpc version (#7457)
883c42b7d disabling unpackto optimization (#7459)
7aae0af30 Remove old GRPC bash script and convert to python3 (#7454)
b057aa917 Grouped anonymous namespaces together, (#7455)
f1b26ff7f Change to GetTypeName (#7453)
9610a666b Generate SLSA signatures for Released zip files (#7450)
1e0f75a64 [WIP] speedup (#7452)
82b75407a Wrap types in namespace for --ts-flat-files and --gen-all (#7451)
f7c511957 Audit and fixups for GCC and Clang (#7212)
a66de58af Partial support for --ts-flat-files and --gen-all (#7446)
a3508f36d [Kotlin] Make sure namespace path exist for code generation (#7357)
137fec716 Stop using __has_trivial_copy on recent clang versions. (#7443)
214125e41 [C#] Rework how sorted vectors are looked up (#7441)
44a7dc999 Define minimum buffer size (#7440)
3cc2daa78 make_span overloads for pointer to vector (#7374) (#7435)
fa1174aa7 [TypeScript] Fix namespaceless schema generation (#7432)
83d4e2a10 Add checks to verifier (#7438)
8a09f3fb0 Fix FlexBuffers JS/TS bug https://github.com/google/flatbuffers/issues/6934 (#7434)
9dbe819ef Add flatc python tests to CI (#7437)
67c414958 Update TypeScriptTest.py to work better cross platform (#7436)
8b8c7dbdf Update gitingore to reflect name change (#7431)
2ee20a5f3 Remove auto including locale functions (#7430)
4be605604 [C++] Set StructDef::has_key property when deserializing from binary schema (#7386) (#7428)
fc5d86f1e [C++] Make template parameter in stl_emulation.h more explicit to avoid conflicts with cpprestsdk U macro (#7424)
9dce287ad Issue#6959 :Updated Automatically generated rust files. (#7425)
7798be3bb avoid zero-as-null-pointer warning (#7423)
966362e07 [C++] Vector of Tables equality (#7415)
a89c279ed [golang] Perform keyword escaping after case conversion (#7421)
a212b3c03 Turn of fail fast for C++ CI
9230f600d Remove stringop-overflow from error (#7422)
c79362156 [golang] Add support for text parsing with json struct tags (#7353)
ee2ced236 Moved TypeScriptTests to python script (#7411)
468c00a3f Rebased: grpc/compiler: Respect filename suffix and extension during code generation (#7414)
47c757f71 Add tests for flatc (#7405)
9a5ff8900 Add FLATBUFFERS_STRICT_MODE (#7408)
950444a34 [TS] Use TextEncoder and TextDecoder (#7400)
30d76198c Compilation issue msys2 #7399 (#7409)
cce3a66f0 Delete .travis directory
8d1cc6ac7 Revert "Compilation issue msys2 (#7403)" (#7407)
5b207639a Update readme.md
359e0f9d6 Revert "grpc/compiler: Respect filename suffix and extension during code generation (#7343)" (#7406)
ebbed0513 Delete cpp-linter.yml
aa395e5a5 (#7323) Rename CMake files according to project name (#7378)
32328075d Fix error msg format when generate GRPC failed (#7350)
97e89c5ac grpc/compiler: Respect filename suffix and extension during code generation (#7343)
5f6672be4 Fix Clang-Cl compile on Windows (#7308)
28e858c85 [TS/Bazel] Minor improvements to typescript.bzl (#7300)
987bebe67 [TS] fix incorrect reverse when writting array of structs (#7271)
ec0129369 Fix FlexBuffers Verifier tracking vectors reuse at wrong offset
50dd385b3 Add missing const (#7401)
da702cfd8 Compilation issue msys2 (#7403)
6e2791640 keep-prefix keeps relative pathing (#7394)
52fce5e53 fix(#7360): grpc used deprecated functions (#7361)
b7f13cd8e cpp_generator: comment out unused parameter to avoid warnings (#7381)
e42985e5a Updated Newtonsoft.Json to 13.0.1 (#7393)
0a8064637 Fix references to LICENSE file (#7377)
b9eea76a8 [Dart] Implement putBool to fix errors when serializing structs with bools (#7359)
1b9030015 Bump Newtonsoft.Json from 12.0.3 to 13.0.1 in /tests/FlatBuffers.Test (#7363)
83a43fc79 Reenable optional json (#7352)
5f0137602 Only include direct included filed (#7348)
9a1913a87 Revert "Implement optional scalars for JSON (#7322)" (#7351)
b4647beb8 Revert "Move reflection_ts_fbs into a separate directory (#7342)" (#7349)
d6060977a Remove asserting in verifier for flattests
987aa5b5e move -Wextra-semi to GCC 8.0+
42acdb63c [TS] Don't generate self-imports with --ts-flat-file (#7340)
0cc1aeb8c [golang] Create missing namespace directory structure (#7324) (#7325)
ba6c67170 [Kotlin] Remove download benchmark files dependency (#7314)
d2f33fc45 Disable Android on Linux CI build
0d1b72cbc [TS] fix ts import path issue (#7298)
9fce2fbf2 replace io/ioutil to os (#7281)
a18ea40d6 Implement optional scalars for JSON (#7322)
090caa280 Move reflection_ts_fbs into a separate directory (#7342)
49e1ea333 Implement optional scalars for Python (#7318)
11a198870 Started implementation for private flags in rust (#7269)
967df08b1 Adds full supposed for Wasm in the swift lib (#7328)
9aa08a429 Use keep case for Rust union discriminant type. (#7321)
9e8c758f5 Add explicit return types to lobster generated code (#7312)
74a25536b Add size check to fix out of bounds read risk (#7304)
12917af8a Update Rust docs page (#7296)
1ea2472f7 [swift] add had<ArrayName> property for arrays to check presence in a message (#7280)
0fe13cb28 Remove span ConstIterator/cbegin()/cend(). (#7295)
385dddc66 Namerkot (#7245)
750dde766 Make `flatc` generate Rust files not requiring `std` (#7273)
9917a168c [swift] Make swift module public (#7274)
76d3cca19 Rust: fix a name conflict when building with "no_std" feature (#7268)
c86e6d0e3 json inf parsing
d34dc32c2 fix include order
234d86c92 fixed off-by-one in parser
746c73b91 Add Annotations for Monster schema and example buffer
0bbfd4b2e fixes for annotator
716521953 Update readme.md (#7257)
a45f564cf [performance] Add aggressive systematic inlining in ByteBuffer and FlatBufferBuilder (#7253)
9d45a6403 more google merge fixes
ccfb4c20b Handle +/-inf in protos (#7256)
7bcd857b8 Specialize CreateVector with std::initializer_list (#7254)
23c8ab34c Swift update performance benchmark infrastructure (#7255)
70002dc5c various fixes for google merge
6e0e79f24 Add test for nested buffer verifier (#7252)
b856368d7 Turn off go modules temporary until we get a proper fix (#7251)
e37156a30 Keep the underlying storage capacity when clearing the FlatBufferBuilder. Gives a significant performance boost for serialisation of many small messages. (#7250)
a10b0e546 Java namer variable keep case (#7249)
275b73994 allow overriding FLATBUFFERS_MAX_ALIGNMENT
9d1ce9a10 Add parameter back to EndVector (#7246)
79afe6c3d Make Java namespaces keep case by default (#7243)
c6dbb2230 Add write permissions for labeller
18bacd3ea Expand test to make sure {}-initializers are properly understood by template. (#7242)
a2c913aec Add -Wnon-virtual-dtor
67b33b294 set workflows permissions to read-only (#7239)
7b5fd2bd0 [Kotlin] Fix key lookup returning null clashing with default value (#7237)
7181d7770 [Java] Fix key lookup returning null clashing with default value (#7236)
7f663b120 Allow CreateVectorOfStrings() to work with any string-type. (#7238)
173ebb694 Fixes a bug where the create function doesnt optional + required items (#7228)
d65823948 [Kotlin] Update gradle to 7.4.1 and simplify config files. (#7231)
ab4bf59e8 remove toascii (#7234)
eee44bbb2 disable cpp-linter (#7229)
a63fa51a1 Create cpp-linter.yml (#7208)
2049e5210 Adds a way to verify/exposes Entities ids (#7221)
832c618f5 Adds implementation flag for swift (#7202)
14615699f Started to migrate to target_compile_options (#7222)
20aad0c41 [C++] stl_emulation span::count_ is not const anymore (#7226) (#7227)
f083b33f2 code gen flexbuffer verifier (#7207)
bf17df346 [C++] generate sorted #include directives (#7213)
35281dedb Fix for [C++] flatc generates invalid Code in the default constructor for structs, when --cpp-field-case-style is used #7209 (#7211)
c9651b742 Add overloads for C# ByteBuffer/FlatBufferBuilder to allow adding vector blocks from ArraySegments or IntPtr (#7193)
26c3b3ada Update codeql.yml
da6e1b985 Update codeql.yml
ad27d751e Added Oss fuzz badge
0aab623cb Create codeql.yml
6a446bdd8 maximize parallel builds in CI (#7206)
21fb5cbbc Create scorecards.yml
0da6f9486 [C++] Static assert on Flatbuffers Version (#7203)
59e971308 reduce fuzzing time to 1 minute in CI
40866a892 fixed padding in struct for annotated binary (#7199)
b71d968fa Apply Namer prefix/suffix to other generators (#7197)
fac0d7be0 Apply Namer to Java. (#7194)
6c5603fd9 [C#] Fix collision of field name and type name (#7149)
2d21853a7 monster fuzzer fix for json default scalars
fec1a8d01 [swift] Add bazel configuration for Swift (#7195)
7fd857623 structured comments (#7192)
a4cb1599d Namerdart (#7187)
ae4ce7265 fuzzed binary annotator (#7188)
e2be0c0b0 Handle root offset and root table vtable invalidation (#7177)
2ad408697 [TS] Fix generation of struct members in object api (#7148)
4213d9105 VerifySizePrefixed (reflection::Schema) and GetAnySizePrefixedRoot added (#7181)
5a13f622c Correctly parse lists of enums in Dart generated code (#7157)
23a7e4e0b Adds no-includes flags to the swift code generator (#7182)
eeb49c275 Move flatbuffer_ts_library to typescript.bzl (#7183)
824763b31 Typo in flatc options (warning-as-errors instead of warnings-as-errors) (#7180)
d3aeee32b Annotated Flatbuffer Binary (#7174)
0bceba24d [Lua] Apply Namer to Lua (#7171)
b8c77d404 Make inclusion of header <optional> opt-out via macro (#7168)
8468eab83 Namersw (#7167)
2b2e8d4ae Nameroverloads (#7164)
b80b32bfa Use DESCRIPTION only if CMake version >= 3.9 (#7166)
Change-Id: Ic2681dabb1a798b7515e62753ee06aecb9933260
git-subtree-dir: third_party/flatbuffers
git-subtree-split: bc44fad35271e43fd7a79b4d691ac9e41708797f
Signed-off-by: Austin Schuh <austin.schuh@bluerivertech.com>
diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp
index c3c322f..b3baa28 100644
--- a/src/idl_gen_swift.cpp
+++ b/src/idl_gen_swift.cpp
@@ -21,21 +21,133 @@
#include "flatbuffers/flatbuffers.h"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
+#include "idl_namer.h"
namespace flatbuffers {
namespace swift {
-inline std::string GenIndirect(const std::string &reading) {
+namespace {
+
+static Namer::Config SwiftDefaultConfig() {
+ return { /*types=*/Case::kKeep,
+ /*constants=*/Case::kLowerCamel,
+ /*methods=*/Case::kLowerCamel,
+ /*functions=*/Case::kLowerCamel,
+ /*fields=*/Case::kLowerCamel,
+ /*variables=*/Case::kLowerCamel,
+ /*variants=*/Case::kLowerCamel,
+ /*enum_variant_seperator=*/".",
+ /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase,
+ /*namespaces=*/Case::kKeep,
+ /*namespace_seperator=*/"_",
+ /*object_prefix=*/"",
+ /*object_suffix=*/"T",
+ /*keyword_prefix=*/"",
+ /*keyword_suffix=*/"_",
+ /*filenames=*/Case::kKeep,
+ /*directories=*/Case::kKeep,
+ /*output_path=*/"",
+ /*filename_suffix=*/"_generated",
+ /*filename_extension=*/".swift" };
+}
+
+static std::set<std::string> SwiftKeywords() {
+ return {
+ "associatedtype",
+ "class",
+ "deinit",
+ "enum",
+ "extension",
+ "fileprivate",
+ "func",
+ "import",
+ "init",
+ "inout",
+ "internal",
+ "let",
+ "open",
+ "operator",
+ "private",
+ "protocol",
+ "public",
+ "rethrows",
+ "static",
+ "struct",
+ "subscript",
+ "typealias",
+ "var",
+ "break",
+ "case",
+ "continue",
+ "default",
+ "defer",
+ "do",
+ "else",
+ "fallthrough",
+ "for",
+ "guard",
+ "if",
+ "in",
+ "repeat",
+ "return",
+ "switch",
+ "where",
+ "while",
+ "Any",
+ "catch",
+ "false",
+ "is",
+ "nil",
+ "super",
+ "self",
+ "Self",
+ "throw",
+ "throws",
+ "true",
+ "try",
+ "associativity",
+ "convenience",
+ "dynamic",
+ "didSet",
+ "final",
+ "get",
+ "infix",
+ "indirect",
+ "lazy",
+ "left",
+ "mutating",
+ "none",
+ "nonmutating",
+ "optional",
+ "override",
+ "postfix",
+ "precedence",
+ "prefix",
+ "Protocol",
+ "required",
+ "right",
+ "set",
+ "Type",
+ "unowned",
+ "weak",
+ "willSet",
+ "Void",
+ };
+}
+
+static std::string GenIndirect(const std::string &reading) {
return "{{ACCESS}}.indirect(" + reading + ")";
}
-inline std::string GenArrayMainBody(const std::string &optional) {
- return "{{ACCESS_TYPE}} func {{VALUENAME}}(at index: Int32) -> "
+static std::string GenArrayMainBody(const std::string &optional) {
+ return "{{ACCESS_TYPE}} func {{FIELDMETHOD}}(at index: Int32) -> "
"{{VALUETYPE}}" +
optional + " { ";
}
+} // namespace
+
class SwiftGenerator : public BaseGenerator {
private:
CodeWriter code_;
@@ -45,92 +157,11 @@
public:
SwiftGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
- : BaseGenerator(parser, path, file_name, "", "_", "swift") {
+ : BaseGenerator(parser, path, file_name, "", "_", "swift"),
+ namer_(WithFlagOptions(SwiftDefaultConfig(), parser.opts, path),
+ SwiftKeywords()) {
namespace_depth = 0;
code_.SetPadding(" ");
- static const char *const keywords[] = {
- "associatedtype",
- "class",
- "deinit",
- "enum",
- "extension",
- "fileprivate",
- "func",
- "import",
- "init",
- "inout",
- "internal",
- "let",
- "open",
- "operator",
- "private",
- "protocol",
- "public",
- "rethrows",
- "static",
- "struct",
- "subscript",
- "typealias",
- "var",
- "break",
- "case",
- "continue",
- "default",
- "defer",
- "do",
- "else",
- "fallthrough",
- "for",
- "guard",
- "if",
- "in",
- "repeat",
- "return",
- "switch",
- "where",
- "while",
- "Any",
- "catch",
- "false",
- "is",
- "nil",
- "super",
- "self",
- "Self",
- "throw",
- "throws",
- "true",
- "try",
- "associativity",
- "convenience",
- "dynamic",
- "didSet",
- "final",
- "get",
- "infix",
- "indirect",
- "lazy",
- "left",
- "mutating",
- "none",
- "nonmutating",
- "optional",
- "override",
- "postfix",
- "precedence",
- "prefix",
- "Protocol",
- "required",
- "right",
- "set",
- "Type",
- "unowned",
- "weak",
- "willSet",
- "Void",
- nullptr,
- };
- for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
bool generate() {
@@ -140,9 +171,14 @@
code_ += "// " + std::string(FlatBuffersGeneratedWarning());
code_ += "// swiftlint:disable all";
code_ += "// swiftformat:disable all\n";
- code_ += "import FlatBuffers\n";
- // Generate code for all the enum declarations.
+ if (parser_.opts.include_dependence_headers || parser_.opts.generate_all) {
+ if (parser_.opts.swift_implementation_only)
+ code_ += "@_implementationOnly \\";
+ code_ += "import FlatBuffers\n";
+ }
+
+ // Generate code for all the enum declarations.
for (auto it = parser_.enums_.vec.begin(); it != parser_.enums_.vec.end();
++it) {
const auto &enum_def = **it;
@@ -183,10 +219,12 @@
// Generates the reader for swift
void GenStructReader(const StructDef &struct_def) {
- auto is_private_access = struct_def.attributes.Lookup("private");
+ const bool is_private_access =
+ parser_.opts.swift_implementation_only ||
+ struct_def.attributes.Lookup("private") != nullptr;
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
GenComment(struct_def.doc_comment);
- code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
+ code_.SetValue("STRUCTNAME", namer_.NamespacedType(struct_def));
code_ +=
"{{ACCESS_TYPE}} struct {{STRUCTNAME}}: NativeStruct, Verifiable, "
"FlatbuffersInitializable\\";
@@ -203,14 +241,14 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
if (!constructor.empty()) constructor += ", ";
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
+ const auto field_var = namer_.Variable(field);
+ const auto type = GenType(field.value.type);
+ code_.SetValue("FIELDVAR", field_var);
if (IsEnum(field.value.type)) {
code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
}
@@ -218,18 +256,20 @@
GenComment(field.doc_comment);
std::string valueType =
IsEnum(field.value.type) ? "{{BASEVALUE}}" : "{{VALUETYPE}}";
- code_ += "private var _{{VALUENAME}}: " + valueType;
- auto accessing_value = IsEnum(field.value.type) ? ".value" : "";
- auto is_bool = IsBool(field.value.type.base_type);
- auto base_value = IsStruct(field.value.type) ? (type + "()")
- : is_bool ? ("0" == field.value.constant ? "false" : "true")
- : field.value.constant;
+ code_ += "private var _{{FIELDVAR}}: " + valueType;
+ const auto accessing_value = IsEnum(field.value.type) ? ".value" : "";
+ const auto is_bool = IsBool(field.value.type.base_type);
+ const auto base_value =
+ IsStruct(field.value.type) ? (type + "()")
+ : is_bool ? ("0" == field.value.constant ? "false" : "true")
+ : field.value.constant;
- main_constructor.push_back("_" + name + " = " + name + accessing_value);
- base_constructor.push_back("_" + name + " = " + base_value);
+ main_constructor.push_back("_" + field_var + " = " + field_var +
+ accessing_value);
+ base_constructor.push_back("_" + field_var + " = " + base_value);
if (field.padding) { GenPadding(field, &padding_id); }
- constructor += name + ": " + type;
+ constructor += field_var + ": " + type;
}
code_ += "";
BuildStructConstructor(struct_def);
@@ -241,23 +281,22 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
- code_.SetValue("VALUETYPE", type);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
+ code_.SetValue("VALUETYPE", GenType(field.value.type));
GenComment(field.doc_comment);
if (!IsEnum(field.value.type)) {
- code_ += GenReaderMainBody() + "_{{VALUENAME}} }";
+ code_ += GenReaderMainBody() + "_{{FIELDVAR}} }";
} else if (IsEnum(field.value.type)) {
code_ +=
- GenReaderMainBody() + "{{VALUETYPE}}(rawValue: _{{VALUENAME}})! }";
+ GenReaderMainBody() + "{{VALUETYPE}}(rawValue: _{{FIELDVAR}})! }";
}
}
code_ += "";
code_ +=
- "public static func verify<T>(_ verifier: inout Verifier, at position: "
+ "{{ACCESS_TYPE}} static func verify<T>(_ verifier: inout Verifier, at "
+ "position: "
"Int, of type: T.Type) throws where T: Verifiable {";
Indent();
code_ +=
@@ -275,22 +314,21 @@
code_ += "let {{ACCESS}} = Struct(bb: bb, position: o)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
- auto type = field.value.type;
- code_.SetValue("VALUENAME", name);
+ const auto type = field.value.type;
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("VALUETYPE", GenType(type));
code_.SetValue("OFFSET", NumToString(field.value.offset));
if (IsScalar(type.base_type)) {
if (IsEnum(type))
code_.SetValue("VALUETYPE", GenTypeBasic(field.value.type, false));
code_ +=
- "_{{VALUENAME}} = {{ACCESS}}.readBuffer(of: {{VALUETYPE}}.self, "
+ "_{{FIELDVAR}} = {{ACCESS}}.readBuffer(of: {{VALUETYPE}}.self, "
"at: {{OFFSET}})";
} else {
code_ +=
- "_{{VALUENAME}} = {{VALUETYPE}}({{ACCESS}}.bb, o: "
+ "_{{FIELDVAR}} = {{VALUETYPE}}({{ACCESS}}.bb, o: "
"{{ACCESS}}.postion + {{OFFSET}})";
}
}
@@ -303,12 +341,11 @@
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto offset = NumToString(field.value.offset);
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
+ const auto offset = NumToString(field.value.offset);
+ const auto type = GenType(field.value.type);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
if (IsEnum(field.value.type)) {
code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
}
@@ -332,7 +369,7 @@
}
if (parser_.opts.generate_object_based_api) {
- GenerateObjectAPIExtensionHeader(NameWrappedInNameSpace(struct_def));
+ GenerateObjectAPIExtensionHeader(namer_.NamespacedType(struct_def));
code_ += "return builder.create(struct: obj)";
Outdent();
code_ += "}";
@@ -343,10 +380,12 @@
// Generates the create function for swift
void GenStructWriter(const StructDef &struct_def) {
- auto is_private_access = struct_def.attributes.Lookup("private");
+ const bool is_private_access =
+ parser_.opts.swift_implementation_only ||
+ struct_def.attributes.Lookup("private") != nullptr;
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
- code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
- code_.SetValue("SHORT_STRUCTNAME", Name(struct_def));
+ code_.SetValue("STRUCTNAME", namer_.NamespacedType(struct_def));
+ code_.SetValue("SHORT_STRUCTNAME", namer_.Method(struct_def));
code_ += "extension {{STRUCTNAME}} {";
Indent();
code_ += "@discardableResult";
@@ -376,7 +415,7 @@
auto &code = *code_ptr;
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
const auto &field_type = field.value.type;
if (IsStruct(field.value.type)) {
@@ -384,14 +423,15 @@
*field_type.struct_def, code_ptr, (nameprefix + field.name),
(object_name + "." + field.name), obj_api_named, is_obj_api);
} else {
- auto name = Name(field);
- auto type = GenType(field.value.type);
+ const auto field_var = namer_.Variable(field);
+ const auto field_field = namer_.Field(field);
+ const auto type = GenType(field.value.type);
if (!is_obj_api) {
- code += nameprefix + name + ": " + type;
+ code += nameprefix + field_var + ": " + type;
if (!IsEnum(field.value.type)) {
code += " = ";
- auto is_bool = IsBool(field.value.type.base_type);
- auto constant =
+ const auto is_bool = IsBool(field.value.type.base_type);
+ const auto constant =
is_bool ? ("0" == field.value.constant ? "false" : "true")
: field.value.constant;
code += constant;
@@ -399,8 +439,8 @@
code += ", ";
continue;
}
- code +=
- nameprefix + name + ": " + obj_api_named + object_name + "." + name;
+ code += nameprefix + field_var + ": " + obj_api_named + object_name +
+ "." + field_field;
code += ", ";
}
}
@@ -410,7 +450,9 @@
// Generates the reader for swift
void GenTable(const StructDef &struct_def) {
- auto is_private_access = struct_def.attributes.Lookup("private");
+ const bool is_private_access =
+ parser_.opts.swift_implementation_only ||
+ struct_def.attributes.Lookup("private") != nullptr;
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
GenObjectHeader(struct_def);
GenTableAccessors(struct_def);
@@ -435,7 +477,7 @@
it != struct_def.fields.vec.end(); ++it) {
const auto &field = **it;
if (field.deprecated) { continue; }
- code_.SetValue("OFFSET_NAME", Name(field));
+ code_.SetValue("OFFSET_NAME", namer_.Variable(field));
code_.SetValue("OFFSET_VALUE", NumToString(field.value.offset));
code_ += "case {{OFFSET_NAME}} = {{OFFSET_VALUE}}";
}
@@ -450,8 +492,8 @@
void GenObjectHeader(const StructDef &struct_def) {
GenComment(struct_def.doc_comment);
- code_.SetValue("SHORT_STRUCTNAME", Name(struct_def));
- code_.SetValue("STRUCTNAME", NameWrappedInNameSpace(struct_def));
+ code_.SetValue("SHORT_STRUCTNAME", namer_.Type(struct_def));
+ code_.SetValue("STRUCTNAME", namer_.NamespacedType(struct_def));
code_.SetValue("OBJECTTYPE", struct_def.fixed ? "Struct" : "Table");
code_.SetValue("MUTABLE", struct_def.fixed ? Mutable() : "");
code_ +=
@@ -468,12 +510,13 @@
if (!struct_def.fixed) {
if (parser_.file_identifier_.length()) {
code_.SetValue("FILENAME", parser_.file_identifier_);
+ code_ += "{{ACCESS_TYPE}} static var id: String { \"{{FILENAME}}\" } ";
code_ +=
"{{ACCESS_TYPE}} static func finish(_ fbb: inout "
"FlatBufferBuilder, end: "
"Offset, prefix: Bool = false) { fbb.finish(offset: end, "
"fileId: "
- "\"{{FILENAME}}\", addPrefix: prefix) }";
+ "{{STRUCTNAME}}.id, addPrefix: prefix) }";
}
code_ +=
"{{ACCESS_TYPE}} static func getRootAs{{SHORT_STRUCTNAME}}(bb: "
@@ -495,7 +538,7 @@
std::vector<std::string> require_fields;
std::vector<std::string> create_func_body;
std::vector<std::string> create_func_header;
- auto should_generate_create = struct_def.fields.vec.size() != 0;
+ const auto should_generate_create = struct_def.fields.vec.size() != 0;
code_.SetValue("NUMBEROFFIELDS", NumToString(struct_def.fields.vec.size()));
code_ +=
@@ -555,14 +598,12 @@
std::string spacing = "";
if (key_field != nullptr && !struct_def.fixed && struct_def.has_key) {
- code_.SetValue("VALUENAME", NameWrappedInNameSpace(struct_def));
- code_.SetValue("SHORT_VALUENAME", Name(struct_def));
code_.SetValue("VOFFSET", NumToString(key_field->value.offset));
- code_ +=
- "{{ACCESS_TYPE}} static func "
- "sortVectorOf{{SHORT_VALUENAME}}(offsets:[Offset], "
- "_ fbb: inout FlatBufferBuilder) -> Offset {";
+ code_ += "{{ACCESS_TYPE}} static func " +
+ namer_.Method("sort_vector_of", struct_def) +
+ "(offsets:[Offset], "
+ "_ fbb: inout FlatBufferBuilder) -> Offset {";
Indent();
code_ += spacing + "var off = offsets";
code_ +=
@@ -573,7 +614,7 @@
code_ += spacing + "return fbb.createVector(ofOffsets: off)";
Outdent();
code_ += "}";
- GenLookup(*key_field);
+ GenLookup(*key_field, namer_.NamespacedType(struct_def));
}
}
@@ -583,42 +624,44 @@
std::string builder_string = ", _ fbb: inout FlatBufferBuilder) { ";
auto &create_func_body = *create_body;
auto &create_func_header = *create_header;
- auto name = Name(field);
- auto type = GenType(field.value.type);
- auto opt_scalar =
+ const auto field_field = namer_.Field(field);
+ const auto field_var = namer_.Variable(field);
+ const auto type = GenType(field.value.type);
+ const auto opt_scalar =
field.IsOptional() && IsScalar(field.value.type.base_type);
- auto nullable_type = opt_scalar ? type + "?" : type;
- code_.SetValue("VALUENAME", name);
+ const auto nullable_type = opt_scalar ? type + "?" : type;
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("VALUETYPE", nullable_type);
- code_.SetValue("OFFSET", name);
+ code_.SetValue("OFFSET", namer_.Field(field));
code_.SetValue("CONSTANT", field.value.constant);
std::string check_if_vector =
(IsVector(field.value.type) || IsArray(field.value.type)) ? "VectorOf("
: "(";
- auto body = "add" + check_if_vector + name + ": ";
+ const auto body = "add" + check_if_vector + field_field + ": ";
code_ += "{{ACCESS_TYPE}} static func " + body + "\\";
- create_func_body.push_back("{{STRUCTNAME}}." + body + name + ", &fbb)");
+ create_func_body.push_back("{{STRUCTNAME}}." + body + field_field +
+ ", &fbb)");
if (IsScalar(field.value.type.base_type) &&
!IsBool(field.value.type.base_type)) {
- std::string is_enum = IsEnum(field.value.type) ? ".rawValue" : "";
- std::string optional_enum =
+ const std::string is_enum = IsEnum(field.value.type) ? ".rawValue" : "";
+ const std::string optional_enum =
IsEnum(field.value.type) ? ("?" + is_enum) : "";
code_ +=
- "{{VALUETYPE}}" + builder_string + "fbb.add(element: {{VALUENAME}}\\";
+ "{{VALUETYPE}}" + builder_string + "fbb.add(element: {{FIELDVAR}}\\";
code_ += field.IsOptional() ? (optional_enum + "\\")
: (is_enum + ", def: {{CONSTANT}}\\");
code_ += ", at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
- auto default_value =
+ const auto default_value =
IsEnum(field.value.type)
? (field.IsOptional() ? "nil" : GenEnumDefaultValue(field))
: field.value.constant;
create_func_header.push_back(
- "" + name + ": " + nullable_type + " = " +
+ "" + field_field + ": " + nullable_type + " = " +
(field.IsOptional() ? "nil" : default_value));
return;
}
@@ -629,48 +672,49 @@
code_.SetValue("CONSTANT", default_value);
code_.SetValue("VALUETYPE", field.IsOptional() ? "Bool?" : "Bool");
- code_ += "{{VALUETYPE}}" + builder_string +
- "fbb.add(element: {{VALUENAME}},\\";
+ code_ +=
+ "{{VALUETYPE}}" + builder_string + "fbb.add(element: {{FIELDVAR}},\\";
code_ += field.IsOptional() ? "\\" : " def: {{CONSTANT}},";
code_ += " at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
create_func_header.push_back(
- name + ": " + nullable_type + " = " +
+ field_var + ": " + nullable_type + " = " +
(field.IsOptional() ? "nil" : default_value));
return;
}
if (IsStruct(field.value.type)) {
- auto create_struct =
- "guard let {{VALUENAME}} = {{VALUENAME}} else { return };"
- " fbb.create(struct: {{VALUENAME}}, position: "
+ const auto create_struct =
+ "guard let {{FIELDVAR}} = {{FIELDVAR}} else { return };"
+ " fbb.create(struct: {{FIELDVAR}}, position: "
"{{TABLEOFFSET}}.{{OFFSET}}.p) }";
code_ += type + "?" + builder_string + create_struct;
/// Optional hard coded since structs are always optional
- create_func_header.push_back(name + ": " + type + "? = nil");
+ create_func_header.push_back(field_var + ": " + type +
+ (field.IsOptional() ? "? = nil" : ""));
return;
}
- auto camel_case_name =
- ConvertCase(name, Case::kLowerCamel) +
+ const auto arg_label =
+ namer_.Variable(field) +
(IsVector(field.value.type) || IsArray(field.value.type)
? "VectorOffset"
: "Offset");
- create_func_header.push_back(camel_case_name + " " + name + ": " +
- "Offset = Offset()");
- auto reader_type =
+ create_func_header.push_back(arg_label + " " + field_var + ": " + "Offset" +
+ (field.IsRequired() ? "" : " = Offset()"));
+ const auto reader_type =
IsStruct(field.value.type) && field.value.type.struct_def->fixed
? "structOffset: {{TABLEOFFSET}}.{{OFFSET}}.p) }"
- : "offset: {{VALUENAME}}, at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
+ : "offset: {{FIELDVAR}}, at: {{TABLEOFFSET}}.{{OFFSET}}.p) }";
code_ += "Offset" + builder_string + "fbb.add(" + reader_type;
- auto vectortype = field.value.type.VectorType();
+ const auto vectortype = field.value.type.VectorType();
if ((vectortype.base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) &&
(IsVector(field.value.type) || IsArray(field.value.type))) {
- auto field_name = NameWrappedInNameSpace(*vectortype.struct_def);
- code_ += "public static func startVectorOf" +
- ConvertCase(name, Case::kUpperCamel) +
+ const auto field_name = namer_.NamespacedType(*vectortype.struct_def);
+ code_ += "{{ACCESS_TYPE}} static func " +
+ namer_.Method("start_vector_of", field_var) +
"(_ size: Int, in builder: inout "
"FlatBufferBuilder) {";
Indent();
@@ -685,25 +729,26 @@
void GenTableReader(const StructDef &struct_def) {
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
GenTableReaderFields(field);
}
}
void GenTableReaderFields(const FieldDef &field) {
- auto offset = NumToString(field.value.offset);
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
+ const auto offset = NumToString(field.value.offset);
+ const auto field_field = namer_.Field(field);
+ const auto type = GenType(field.value.type);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
+ code_.SetValue("FIELDMETHOD", namer_.Method(field));
code_.SetValue("VALUETYPE", type);
- code_.SetValue("OFFSET", name);
+ code_.SetValue("OFFSET", namer_.Constant(field.name));
code_.SetValue("CONSTANT", field.value.constant);
bool opt_scalar =
field.IsOptional() && IsScalar(field.value.type.base_type);
std::string def_Val = opt_scalar ? "nil" : "{{CONSTANT}}";
std::string optional = opt_scalar ? "?" : "";
- auto const_string = "return o == 0 ? " + def_Val + " : ";
+ const auto const_string = "return o == 0 ? " + def_Val + " : ";
GenComment(field.doc_comment);
if (IsScalar(field.value.type.base_type) && !IsEnum(field.value.type) &&
!IsBool(field.value.type.base_type)) {
@@ -728,7 +773,7 @@
}
if (IsEnum(field.value.type)) {
- auto default_value =
+ const auto default_value =
field.IsOptional() ? "nil" : GenEnumDefaultValue(field);
code_.SetValue("BASEVALUE", GenTypeBasic(field.value.type, false));
code_ += GenReaderMainBody(optional) + "\\";
@@ -739,16 +784,15 @@
return;
}
- std::string is_required = field.IsRequired() ? "!" : "?";
- auto required_reader = field.IsRequired() ? "return " : const_string;
+ const std::string is_required = field.IsRequired() ? "!" : "?";
+ const auto required_reader = field.IsRequired() ? "return " : const_string;
if (IsStruct(field.value.type) && field.value.type.struct_def->fixed) {
code_.SetValue("VALUETYPE", GenType(field.value.type));
code_.SetValue("CONSTANT", "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader +
"{{ACCESS}}.readBuffer(of: {{VALUETYPE}}.self, at: o) }";
- code_.SetValue("VALUENAME",
- "mutable" + ConvertCase(name, Case::kUpperCamel));
+ code_.SetValue("FIELDVAR", namer_.Variable("mutable", field_field));
code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable());
code_.SetValue("CONSTANT", "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader +
@@ -765,12 +809,12 @@
break;
case BASE_TYPE_STRING: {
- auto default_string = "\"" + field.value.constant + "\"";
+ const auto default_string = "\"" + field.value.constant + "\"";
code_.SetValue("VALUETYPE", GenType(field.value.type));
code_.SetValue("CONSTANT", field.IsDefault() ? default_string : "nil");
code_ += GenReaderMainBody(is_required) + GenOffset() +
required_reader + "{{ACCESS}}.string(at: o) }";
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}SegmentArray: [UInt8]" +
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}SegmentArray: [UInt8]" +
is_required +
" { return "
"{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v) }";
@@ -781,7 +825,7 @@
case BASE_TYPE_UNION:
code_.SetValue("CONSTANT", "nil");
code_ +=
- "{{ACCESS_TYPE}} func {{VALUENAME}}<T: "
+ "{{ACCESS_TYPE}} func {{FIELDVAR}}<T: "
"FlatbuffersInitializable>(type: "
"T.Type) -> T" +
is_required + " { " + GenOffset() + required_reader +
@@ -793,20 +837,22 @@
void GenTableReaderVectorFields(const FieldDef &field) {
std::string const_string = "return o == 0 ? {{CONSTANT}} : ";
- auto vectortype = field.value.type.VectorType();
+ const auto vectortype = field.value.type.VectorType();
code_.SetValue("SIZE", NumToString(InlineSize(vectortype)));
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}Count: Int32 { " + GenOffset() +
+ code_.SetValue("HAS_FIELDVAR", namer_.Variable("has", field));
+ code_ += "{{ACCESS_TYPE}} var {{HAS_FIELDVAR}}: Bool { " + GenOffset() +
+ "return o == 0 ? false : true }";
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}Count: Int32 { " + GenOffset() +
"return o == 0 ? 0 : {{ACCESS}}.vector(count: o) }";
- code_.SetValue("CONSTANT",
- IsScalar(vectortype.base_type) == true ? "0" : "nil");
- auto nullable = IsScalar(vectortype.base_type) == true ? "" : "?";
- nullable = IsEnum(vectortype) == true ? "?" : nullable;
+ code_.SetValue("CONSTANT", IsScalar(vectortype.base_type) ? "0" : "nil");
+ const auto nullable =
+ IsScalar(vectortype.base_type) && !IsEnum(vectortype) ? "" : "?";
if (vectortype.base_type != BASE_TYPE_UNION) {
code_ += GenArrayMainBody(nullable) + GenOffset() + "\\";
} else {
code_ +=
- "{{ACCESS_TYPE}} func {{VALUENAME}}<T: FlatbuffersInitializable>(at "
+ "{{ACCESS_TYPE}} func {{FIELDVAR}}<T: FlatbuffersInitializable>(at "
"index: "
"Int32, type: T.Type) -> T? { " +
GenOffset() + "\\";
@@ -825,7 +871,7 @@
"{{ACCESS}}.directRead(of: {{VALUETYPE}}.self, offset: "
"{{ACCESS}}.vector(at: o) + index * {{SIZE}}) }";
code_ +=
- "{{ACCESS_TYPE}} var {{VALUENAME}}: [{{VALUETYPE}}] { return "
+ "{{ACCESS_TYPE}} var {{FIELDVAR}}: [{{VALUETYPE}}] { return "
"{{ACCESS}}.getVector(at: {{TABLEOFFSET}}.{{OFFSET}}.v) ?? [] }";
if (parser_.opts.mutable_buffer) code_ += GenMutateArray();
return;
@@ -836,8 +882,7 @@
code_ +=
"{{ACCESS}}.directRead(of: {{VALUETYPE}}.self, offset: "
"{{ACCESS}}.vector(at: o) + index * {{SIZE}}) }";
- code_.SetValue("VALUENAME",
- "mutable" + ConvertCase(Name(field), Case::kUpperCamel));
+ code_.SetValue("FIELDMETHOD", namer_.Method("mutable", field));
code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable());
code_ += GenArrayMainBody(nullable) + GenOffset() + const_string +
GenConstructor("{{ACCESS}}.vector(at: o) + index * {{SIZE}}");
@@ -872,10 +917,10 @@
code_ += GenConstructor(
"{{ACCESS}}.indirect({{ACCESS}}.vector(at: o) + index * "
"{{SIZE}})");
- auto &sd = *field.value.type.struct_def;
- auto &fields = sd.fields.vec;
+ const auto &sd = *field.value.type.struct_def;
+ const auto &fields = sd.fields.vec;
for (auto kit = fields.begin(); kit != fields.end(); ++kit) {
- auto &key_field = **kit;
+ const auto &key_field = **kit;
if (key_field.key) {
GenByKeyFunctions(key_field);
break;
@@ -889,13 +934,12 @@
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
code_.SetValue("RAWVALUENAME", field.name);
- code_.SetValue("VALUENAME", name);
- code_ += "case {{VALUENAME}} = \"{{RAWVALUENAME}}\"";
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
+ code_ += "case {{FIELDVAR}} = \"{{RAWVALUENAME}}\"";
}
Outdent();
code_ += "}";
@@ -903,8 +947,8 @@
void GenerateEncoderUnionBody(const FieldDef &field) {
EnumDef &union_def = *field.value.type.enum_def;
- auto is_vector = field.value.type.base_type == BASE_TYPE_VECTOR ||
- field.value.type.base_type == BASE_TYPE_ARRAY;
+ const auto is_vector = field.value.type.base_type == BASE_TYPE_VECTOR ||
+ field.value.type.base_type == BASE_TYPE_ARRAY;
if (field.value.type.base_type == BASE_TYPE_UTYPE ||
(is_vector &&
field.value.type.VectorType().base_type == BASE_TYPE_UTYPE))
@@ -912,28 +956,25 @@
if (is_vector) {
code_ +=
"var enumsEncoder = container.nestedUnkeyedContainer(forKey: "
- ".{{VALUENAME}}Type)";
+ ".{{FIELDVAR}}Type)";
code_ +=
"var contentEncoder = container.nestedUnkeyedContainer(forKey: "
- ".{{VALUENAME}})";
- code_ += "for index in 0..<{{VALUENAME}}Count {";
+ ".{{FIELDVAR}})";
+ code_ += "for index in 0..<{{FIELDVAR}}Count {";
Indent();
- code_ +=
- "guard let type = {{VALUENAME}}Type(at: index) else { continue }";
+ code_ += "guard let type = {{FIELDVAR}}Type(at: index) else { continue }";
code_ += "try enumsEncoder.encode(type)";
code_ += "switch type {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
const auto &ev = **it;
-
- auto name = Name(ev);
- auto type = GenType(ev.union_type);
- code_.SetValue("KEY", name);
+ const auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
code_ += "case .{{KEY}}:";
Indent();
- code_ += "let _v = {{VALUENAME}}(at: index, type: {{VALUETYPE}}.self)";
+ code_ += "let _v = {{FIELDVAR}}(at: index, type: {{VALUETYPE}}.self)";
code_ += "try contentEncoder.encode(_v)";
Outdent();
}
@@ -944,20 +985,18 @@
return;
}
- code_ += "switch {{VALUENAME}}Type {";
+ code_ += "switch {{FIELDVAR}}Type {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
const auto &ev = **it;
-
- auto name = Name(ev);
- auto type = GenType(ev.union_type);
- code_.SetValue("KEY", name);
+ const auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
code_ += "case .{{KEY}}:";
Indent();
- code_ += "let _v = {{VALUENAME}}(type: {{VALUETYPE}}.self)";
- code_ += "try container.encodeIfPresent(_v, forKey: .{{VALUENAME}})";
+ code_ += "let _v = {{FIELDVAR}}(type: {{VALUETYPE}}.self)";
+ code_ += "try container.encodeIfPresent(_v, forKey: .{{FIELDVAR}})";
Outdent();
}
code_ += "default: break;";
@@ -968,33 +1007,31 @@
code_ += "var container = encoder.container(keyedBy: CodingKeys.self)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
- auto type = field.value.type;
+ const auto type = field.value.type;
- auto is_non_union_vector =
+ const auto is_non_union_vector =
(field.value.type.base_type == BASE_TYPE_ARRAY ||
field.value.type.base_type == BASE_TYPE_VECTOR) &&
field.value.type.VectorType().base_type != BASE_TYPE_UTYPE;
- code_.SetValue("RAWVALUENAME", field.name);
- code_.SetValue("VALUENAME", name);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("CONSTANT", field.value.constant);
bool should_indent = true;
if (is_non_union_vector) {
- code_ += "if {{VALUENAME}}Count > 0 {";
+ code_ += "if {{FIELDVAR}}Count > 0 {";
} else if (IsEnum(type) && !field.IsOptional()) {
code_.SetValue("CONSTANT", GenEnumDefaultValue(field));
- code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else if (IsScalar(type.base_type) && !IsEnum(type) &&
!IsBool(type.base_type) && !field.IsOptional()) {
- code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else if (IsBool(type.base_type) && !field.IsOptional()) {
std::string default_value =
"0" == field.value.constant ? "false" : "true";
code_.SetValue("CONSTANT", default_value);
- code_ += "if {{VALUENAME}} != {{CONSTANT}} {";
+ code_ += "if {{FIELDVAR}} != {{CONSTANT}} {";
} else {
should_indent = false;
}
@@ -1007,17 +1044,17 @@
IsEnum(type.VectorType()))) {
code_ +=
"var contentEncoder = container.nestedUnkeyedContainer(forKey: "
- ".{{VALUENAME}})";
- code_ += "for index in 0..<{{VALUENAME}}Count {";
+ ".{{FIELDVAR}})";
+ code_ += "for index in 0..<{{FIELDVAR}}Count {";
Indent();
- code_ += "guard let type = {{VALUENAME}}(at: index) else { continue }";
+ code_ += "guard let type = {{FIELDVAR}}(at: index) else { continue }";
code_ += "try contentEncoder.encode(type)";
Outdent();
code_ += "}";
} else {
code_ +=
- "try container.encodeIfPresent({{VALUENAME}}, forKey: "
- ".{{VALUENAME}})";
+ "try container.encodeIfPresent({{FIELDVAR}}, forKey: "
+ ".{{FIELDVAR}})";
}
if (should_indent) Outdent();
@@ -1034,7 +1071,7 @@
code_ += "";
if (struct_def.fields.vec.empty() == false) GenerateCodingKeys(struct_def);
- code_ += "public func encode(to encoder: Encoder) throws {";
+ code_ += "{{ACCESS_TYPE}} func encode(to encoder: Encoder) throws {";
Indent();
if (struct_def.fields.vec.empty() == false) GenerateEncoderBody(struct_def);
Outdent();
@@ -1046,20 +1083,20 @@
void GenerateVerifier(const StructDef &struct_def) {
code_ +=
- "public static func verify<T>(_ verifier: inout Verifier, at position: "
+ "{{ACCESS_TYPE}} static func verify<T>(_ verifier: inout Verifier, at "
+ "position: "
"Int, of type: T.Type) throws where T: Verifiable {";
Indent();
code_ += "var _v = try verifier.visitTable(at: position)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto offset = NumToString(field.value.offset);
- auto name = Name(field);
+ const auto offset = NumToString(field.value.offset);
- code_.SetValue("VALUENAME", name);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
code_.SetValue("VALUETYPE", GenerateVerifierType(field));
- code_.SetValue("OFFSET", name);
+ code_.SetValue("OFFSET", namer_.Field(field));
code_.SetValue("ISREQUIRED", field.IsRequired() ? "true" : "false");
if (IsUnion(field.value.type)) {
@@ -1069,7 +1106,7 @@
code_ +=
"try _v.visit(field: {{TABLEOFFSET}}.{{OFFSET}}.p, fieldName: "
- "\"{{VALUENAME}}\", required: {{ISREQUIRED}}, type: "
+ "\"{{FIELDVAR}}\", required: {{ISREQUIRED}}, type: "
"{{VALUETYPE}}.self)";
}
code_ += "_v.finish()";
@@ -1078,28 +1115,27 @@
}
void GenerateUnionTypeVerifier(const FieldDef &field) {
- auto is_vector = IsVector(field.value.type) || IsArray(field.value.type);
+ const auto is_vector =
+ IsVector(field.value.type) || IsArray(field.value.type);
if (field.value.type.base_type == BASE_TYPE_UTYPE ||
(is_vector &&
field.value.type.VectorType().base_type == BASE_TYPE_UTYPE))
return;
EnumDef &union_def = *field.value.type.enum_def;
- code_.SetValue("VALUETYPE", NameWrappedInNameSpace(union_def));
+ code_.SetValue("VALUETYPE", namer_.NamespacedType(union_def));
code_.SetValue("FUNCTION_NAME", is_vector ? "visitUnionVector" : "visit");
code_ +=
"try _v.{{FUNCTION_NAME}}(unionKey: {{TABLEOFFSET}}.{{OFFSET}}Type.p, "
"unionField: {{TABLEOFFSET}}.{{OFFSET}}.p, unionKeyName: "
- "\"{{VALUENAME}}Type\", fieldName: \"{{VALUENAME}}\", required: "
+ "\"{{FIELDVAR}}Type\", fieldName: \"{{FIELDVAR}}\", required: "
"{{ISREQUIRED}}, completion: { (verifier, key: {{VALUETYPE}}, pos) in";
Indent();
code_ += "switch key {";
for (auto it = union_def.Vals().begin(); it != union_def.Vals().end();
++it) {
const auto &ev = **it;
-
- auto name = Name(ev);
- auto type = GenType(ev.union_type);
- code_.SetValue("KEY", name);
+ const auto type = GenType(ev.union_type);
+ code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUETYPE", type);
code_ += "case .{{KEY}}:";
Indent();
@@ -1125,11 +1161,11 @@
}
std::string GenerateVerifierType(const FieldDef &field) {
- auto type = field.value.type;
- auto is_vector = IsVector(type) || IsArray(type);
+ const auto type = field.value.type;
+ const auto is_vector = IsVector(type) || IsArray(type);
if (is_vector) {
- auto vector_type = field.value.type.VectorType();
+ const auto vector_type = field.value.type.VectorType();
return "ForwardOffset<Vector<" +
GenerateNestedVerifierTypes(vector_type) + ", " +
GenType(vector_type) + ">>";
@@ -1139,7 +1175,7 @@
}
std::string GenerateNestedVerifierTypes(const Type &type) {
- auto string_type = GenType(type);
+ const auto string_type = GenType(type);
if (IsScalar(type.base_type)) { return string_type; }
@@ -1153,7 +1189,7 @@
void GenByKeyFunctions(const FieldDef &key_field) {
code_.SetValue("TYPE", GenType(key_field.value.type));
code_ +=
- "{{ACCESS_TYPE}} func {{VALUENAME}}By(key: {{TYPE}}) -> {{VALUETYPE}}? "
+ "{{ACCESS_TYPE}} func {{FIELDVAR}}By(key: {{TYPE}}) -> {{VALUETYPE}}? "
"{ \\";
code_ += GenOffset() +
"return o == 0 ? nil : {{VALUETYPE}}.lookupByKey(vector: "
@@ -1162,11 +1198,11 @@
void GenEnum(const EnumDef &enum_def) {
if (enum_def.generated) return;
- auto is_private_access = enum_def.attributes.Lookup("private");
+ const auto is_private_access = enum_def.attributes.Lookup("private");
code_.SetValue("ENUM_TYPE",
enum_def.is_union ? "UnionEnum" : "Enum, Verifiable");
code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public");
- code_.SetValue("ENUM_NAME", NameWrappedInNameSpace(enum_def));
+ code_.SetValue("ENUM_NAME", namer_.NamespacedType(enum_def));
code_.SetValue("BASE_TYPE", GenTypeBasic(enum_def.underlying_type, false));
GenComment(enum_def.doc_comment);
code_ +=
@@ -1189,15 +1225,16 @@
"{{ACCESS_TYPE}} var value: {{BASE_TYPE}} { return self.rawValue }";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
- auto name = Name(ev);
- code_.SetValue("KEY", name);
+ code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("VALUE", enum_def.ToString(ev));
GenComment(ev.doc_comment);
code_ += "case {{KEY}} = {{VALUE}}";
}
code_ += "";
- AddMinOrMaxEnumValue(Name(*enum_def.MaxValue()), "max");
- AddMinOrMaxEnumValue(Name(*enum_def.MinValue()), "min");
+ AddMinOrMaxEnumValue(namer_.LegacySwiftVariant(*enum_def.MaxValue()),
+ "max");
+ AddMinOrMaxEnumValue(namer_.LegacySwiftVariant(*enum_def.MinValue()),
+ "min");
Outdent();
code_ += "}\n";
if (parser_.opts.gen_json_coders) EnumEncoder(enum_def);
@@ -1235,8 +1272,7 @@
code_ += "switch self {";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
const auto &ev = **it;
- auto name = Name(ev);
- code_.SetValue("KEY", name);
+ code_.SetValue("KEY", namer_.LegacySwiftVariant(ev));
code_.SetValue("RAWKEY", ev.name);
code_ += "case .{{KEY}}: try container.encode(\"{{RAWKEY}}\")";
}
@@ -1249,18 +1285,18 @@
// MARK: - Object API
- void GenerateObjectAPIExtensionHeader(std::string name) {
+ void GenerateObjectAPIExtensionHeader(std::string type_name) {
code_ += "\n";
- code_ += "{{ACCESS_TYPE}} mutating func unpack() -> " + name + " {";
+ code_ += "{{ACCESS_TYPE}} mutating func unpack() -> " + type_name + " {";
Indent();
- code_ += "return " + name + "(&self)";
+ code_ += "return " + type_name + "(&self)";
Outdent();
code_ += "}";
code_ +=
"{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
"obj: "
"inout " +
- name + "?) -> Offset {";
+ type_name + "?) -> Offset {";
Indent();
code_ += "guard var obj = obj else { return Offset() }";
code_ += "return pack(&builder, obj: &obj)";
@@ -1271,7 +1307,7 @@
"{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, "
"obj: "
"inout " +
- name + ") -> Offset {";
+ type_name + ") -> Offset {";
Indent();
}
@@ -1281,40 +1317,39 @@
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
+ const auto type = GenType(field.value.type);
+ code_.SetValue("FIELDVAR", namer_.Variable(field));
if (IsStruct(field.value.type)) {
- code_ += "var _v{{VALUENAME}} = _t.{{VALUENAME}}";
- code_ += "_{{VALUENAME}} = _v{{VALUENAME}}.unpack()";
+ code_ += "var _v{{FIELDVAR}} = _t.{{FIELDVAR}}";
+ code_ += "_{{FIELDVAR}} = _v{{FIELDVAR}}.unpack()";
continue;
}
std::string is_enum = IsEnum(field.value.type) ? ".value" : "";
- code_ += "_{{VALUENAME}} = _t.{{VALUENAME}}" + is_enum;
+ code_ += "_{{FIELDVAR}} = _t.{{FIELDVAR}}" + is_enum;
}
Outdent();
code_ += "}\n";
}
void GenObjectAPI(const StructDef &struct_def) {
- code_ += "{{ACCESS_TYPE}} class " + ObjectAPIName("{{STRUCTNAME}}") +
- ": NativeObject {\n";
+ code_ += "{{ACCESS_TYPE}} class " +
+ namer_.NamespacedObjectType(struct_def) + ": NativeObject {\n";
std::vector<std::string> buffer_constructor;
std::vector<std::string> base_constructor;
Indent();
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
BuildObjectAPIConstructorBody(field, struct_def.fixed, buffer_constructor,
base_constructor);
}
code_ += "";
BuildObjectConstructor(buffer_constructor,
- "_ _t: inout " + NameWrappedInNameSpace(struct_def));
+ "_ _t: inout " + namer_.NamespacedType(struct_def));
BuildObjectConstructor(base_constructor);
if (!struct_def.fixed)
code_ +=
@@ -1326,35 +1361,37 @@
}
void GenerateObjectAPITableExtension(const StructDef &struct_def) {
- GenerateObjectAPIExtensionHeader(ObjectAPIName("{{STRUCTNAME}}"));
+ GenerateObjectAPIExtensionHeader(namer_.NamespacedObjectType(struct_def));
std::vector<std::string> unpack_body;
std::string builder = ", &builder)";
for (auto it = struct_def.fields.vec.begin();
it != struct_def.fields.vec.end(); ++it) {
- auto &field = **it;
+ const auto &field = **it;
if (field.deprecated) continue;
- auto name = Name(field);
- auto type = GenType(field.value.type);
+ const auto field_var = namer_.Variable(field);
+ const auto field_field = namer_.Field(field);
+ const auto field_method = namer_.Method(field);
+ const auto type = GenType(field.value.type);
std::string check_if_vector =
(IsVector(field.value.type) || IsArray(field.value.type))
? "VectorOf("
: "(";
- std::string body = "add" + check_if_vector + name + ": ";
+ std::string body = "add" + check_if_vector + field_method + ": ";
switch (field.value.type.base_type) {
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
case BASE_TYPE_VECTOR: {
- GenerateVectorObjectAPITableExtension(field, name, type);
- unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + name +
+ GenerateVectorObjectAPITableExtension(field);
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + field_var +
builder);
break;
}
case BASE_TYPE_UNION: {
- code_ += "let __" + name + " = obj." + name +
+ code_ += "let __" + field_var + " = obj." + field_var +
"?.pack(builder: &builder) ?? Offset()";
- unpack_body.push_back("if let o = obj." + name + "?.type {");
- unpack_body.push_back(" {{STRUCTNAME}}.add(" + name + "Type: o" +
- builder);
- unpack_body.push_back(" {{STRUCTNAME}}." + body + "__" + name +
+ unpack_body.push_back("if let o = obj." + field_var + "?.type {");
+ unpack_body.push_back(" {{STRUCTNAME}}.add(" + field_var +
+ "Type: o" + builder);
+ unpack_body.push_back(" {{STRUCTNAME}}." + body + "__" + field_var +
builder);
unpack_body.push_back("}\n");
break;
@@ -1368,31 +1405,31 @@
GenerateStructArgs(*field.value.type.struct_def, &code, "", "",
"$0", true);
code = code.substr(0, code.size() - 2);
- unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." + name +
- builder);
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." +
+ field_field + builder);
} else {
- code_ += "let __" + name + " = " + type +
- ".pack(&builder, obj: &obj." + name + ")";
- unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + name +
+ code_ += "let __" + field_var + " = " + type +
+ ".pack(&builder, obj: &obj." + field_field + ")";
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + field_var +
builder);
}
break;
}
case BASE_TYPE_STRING: {
- unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + name +
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "__" + field_var +
builder);
if (field.IsRequired()) {
- code_ +=
- "let __" + name + " = builder.create(string: obj." + name + ")";
+ code_ += "let __" + field_var + " = builder.create(string: obj." +
+ field_field + ")";
} else {
- BuildingOptionalObjects(name, "builder.create(string: s)");
+ BuildingOptionalObjects(field_field, "builder.create(string: s)");
}
break;
}
case BASE_TYPE_UTYPE: break;
default:
- unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." + name +
- builder);
+ unpack_body.push_back("{{STRUCTNAME}}." + body + "obj." +
+ field_field + builder);
}
}
code_ += "let __root = {{STRUCTNAME}}.start{{SHORT_STRUCTNAME}}(&builder)";
@@ -1405,79 +1442,79 @@
code_ += "}";
}
- void GenerateVectorObjectAPITableExtension(const FieldDef &field,
- const std::string &name,
- const std::string &type) {
- auto vectortype = field.value.type.VectorType();
+ void GenerateVectorObjectAPITableExtension(const FieldDef &field_def) {
+ const Type &field_type = field_def.value.type;
+ const auto type = GenType(field_type);
+ const auto var = namer_.Variable(field_def);
+ const auto field = namer_.Field(field_def);
+
+ const auto vectortype = field_type.VectorType();
switch (vectortype.base_type) {
case BASE_TYPE_UNION: {
- code_ += "var __" + name + "__: [Offset] = []";
- code_ += "for i in obj." + name + " {";
+ code_ += "var __" + var + "__: [Offset] = []";
+ code_ += "for i in obj." + var + " {";
Indent();
code_ += "guard let off = i?.pack(builder: &builder) else { continue }";
- code_ += "__" + name + "__.append(off)";
+ code_ += "__" + var + "__.append(off)";
Outdent();
code_ += "}";
- code_ += "let __" + name + " = builder.createVector(ofOffsets: __" +
- name + "__)";
- code_ += "let __" + name + "Type = builder.createVector(obj." + name +
+ code_ += "let __" + var + " = builder.createVector(ofOffsets: __" +
+ var + "__)";
+ code_ += "let __" + var + "Type = builder.createVector(obj." + field +
".compactMap { $0?.type })";
break;
}
case BASE_TYPE_UTYPE: break;
case BASE_TYPE_STRUCT: {
- if (field.value.type.struct_def &&
- !field.value.type.struct_def->fixed) {
- code_ += "var __" + name + "__: [Offset] = []";
- code_ += "for var i in obj." + name + " {";
+ if (field_type.struct_def && !field_type.struct_def->fixed) {
+ code_ += "var __" + var + "__: [Offset] = []";
+ code_ += "for var i in obj." + var + " {";
Indent();
code_ +=
- "__" + name + "__.append(" + type + ".pack(&builder, obj: &i))";
+ "__" + var + "__.append(" + type + ".pack(&builder, obj: &i))";
Outdent();
code_ += "}";
- code_ += "let __" + name + " = builder.createVector(ofOffsets: __" +
- name + "__)";
+ code_ += "let __" + var + " = builder.createVector(ofOffsets: __" +
+ var + "__)";
} else {
- code_ += "{{STRUCTNAME}}.startVectorOf" +
- ConvertCase(name, Case::kUpperCamel) + "(obj." + name +
- ".count, in: &builder)";
+ code_ += "{{STRUCTNAME}}." + namer_.Method("start_vector_of", var) +
+ "(obj." + field + ".count, in: &builder)";
std::string code;
- GenerateStructArgs(*field.value.type.struct_def, &code, "", "", "_o",
- true);
+ GenerateStructArgs(*field_type.struct_def, &code, "", "", "_o", true);
code = code.substr(0, code.size() - 2);
- code_ += "for i in obj." + name + " {";
+ code_ += "for i in obj." + field + " {";
Indent();
code_ += "guard let _o = i else { continue }";
code_ += "builder.create(struct: _o)";
Outdent();
code_ += "}";
- code_ += "let __" + name + " = builder.endVector(len: obj." + name +
+ code_ += "let __" + var + " = builder.endVector(len: obj." + field +
".count)";
}
break;
}
case BASE_TYPE_STRING: {
- code_ += "let __" + name + " = builder.createVector(ofStrings: obj." +
- name + ".compactMap({ $0 }) )";
+ code_ += "let __" + var + " = builder.createVector(ofStrings: obj." +
+ var + ".compactMap({ $0 }) )";
break;
}
default: {
- code_ += "let __" + name + " = builder.createVector(obj." + name + ")";
+ code_ += "let __" + var + " = builder.createVector(obj." + field + ")";
break;
}
}
}
- void BuildingOptionalObjects(const std::string &name,
+ void BuildingOptionalObjects(const std::string &var,
const std::string &body_front) {
- code_ += "let __" + name + ": Offset";
- code_ += "if let s = obj." + name + " {";
+ code_ += "let __" + var + ": Offset";
+ code_ += "if let s = obj." + var + " {";
Indent();
- code_ += "__" + name + " = " + body_front;
+ code_ += "__" + var + " = " + body_front;
Outdent();
code_ += "} else {";
Indent();
- code_ += "__" + name + " = Offset()";
+ code_ += "__" + var + " = Offset()";
Outdent();
code_ += "}";
code_ += "";
@@ -1497,120 +1534,125 @@
const FieldDef &field, bool is_fixed,
std::vector<std::string> &buffer_constructor,
std::vector<std::string> &base_constructor) {
- auto name = Name(field);
- auto type = GenType(field.value.type);
- code_.SetValue("VALUENAME", name);
+ const auto field_field = namer_.Field(field);
+ const auto field_var = namer_.Variable(field);
+ const auto type = GenType(field.value.type);
+ code_.SetValue("FIELDVAR", field_field);
code_.SetValue("VALUETYPE", type);
std::string is_required = field.IsRequired() ? "" : "?";
switch (field.value.type.base_type) {
case BASE_TYPE_STRUCT: {
- type = GenType(field.value.type, true);
- code_.SetValue("VALUETYPE", type);
- auto optional =
+ const auto objtype = GenType(field.value.type, true);
+ code_.SetValue("VALUETYPE", objtype);
+ const auto optional =
(field.value.type.struct_def && field.value.type.struct_def->fixed);
std::string question_mark =
(field.IsRequired() || (optional && is_fixed) ? "" : "?");
code_ +=
- "{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}" + question_mark;
- base_constructor.push_back("" + name + " = " + type + "()");
+ "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}" + question_mark;
+ base_constructor.push_back("" + field_var + " = " + objtype + "()");
if (field.value.type.struct_def->fixed) {
- buffer_constructor.push_back("" + name + " = _t." + name);
+ buffer_constructor.push_back("" + field_var + " = _t." + field_field);
} else {
- buffer_constructor.push_back("var __" + name + " = _t." + name);
+ buffer_constructor.push_back("var __" + field_var + " = _t." +
+ field_field);
buffer_constructor.push_back(
- "" + name + " = __" + name +
+ "" + field_var + " = __" + field_var +
(field.IsRequired() ? "!" : question_mark) + ".unpack()");
}
break;
}
case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();
case BASE_TYPE_VECTOR: {
- BuildObjectAPIConstructorBodyVectors(field, name, buffer_constructor,
+ BuildObjectAPIConstructorBodyVectors(field, buffer_constructor,
base_constructor, " ");
break;
}
case BASE_TYPE_STRING: {
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: String" + is_required;
- buffer_constructor.push_back(name + " = _t." + name);
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: String" + is_required;
+ buffer_constructor.push_back(field_var + " = _t." + field_field);
if (field.IsRequired()) {
std::string default_value =
field.IsDefault() ? field.value.constant : "";
- base_constructor.push_back(name + " = \"" + default_value + "\"");
+ base_constructor.push_back(field_var + " = \"" + default_value +
+ "\"");
break;
}
if (field.IsDefault() && !field.IsRequired()) {
std::string value = field.IsDefault() ? field.value.constant : "nil";
- base_constructor.push_back(name + " = \"" + value + "\"");
+ base_constructor.push_back(field_var + " = \"" + value + "\"");
}
break;
}
case BASE_TYPE_UTYPE: break;
case BASE_TYPE_UNION: {
- BuildUnionEnumSwitchCase(*field.value.type.enum_def, name,
+ BuildUnionEnumSwitchCase(*field.value.type.enum_def, field_var,
buffer_constructor);
break;
}
default: {
- buffer_constructor.push_back(name + " = _t." + name);
+ buffer_constructor.push_back(field_var + " = _t." + field_field);
std::string nullable = field.IsOptional() ? "?" : "";
if (IsScalar(field.value.type.base_type) &&
!IsBool(field.value.type.base_type) && !IsEnum(field.value.type)) {
- code_ +=
- "{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}" + nullable;
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}" + nullable;
if (!field.IsOptional())
- base_constructor.push_back(name + " = " + field.value.constant);
+ base_constructor.push_back(field_var + " = " +
+ field.value.constant);
break;
}
if (IsEnum(field.value.type)) {
- auto default_value = IsEnum(field.value.type)
- ? GenEnumDefaultValue(field)
- : field.value.constant;
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}";
- base_constructor.push_back(name + " = " + default_value);
+ const auto default_value = IsEnum(field.value.type)
+ ? GenEnumDefaultValue(field)
+ : field.value.constant;
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}";
+ base_constructor.push_back(field_var + " = " + default_value);
break;
}
if (IsBool(field.value.type.base_type)) {
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: Bool" + nullable;
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: Bool" + nullable;
std::string default_value =
"0" == field.value.constant ? "false" : "true";
if (!field.IsOptional())
- base_constructor.push_back(name + " = " + default_value);
+ base_constructor.push_back(field_var + " = " + default_value);
}
}
}
}
void BuildObjectAPIConstructorBodyVectors(
- const FieldDef &field, const std::string &name,
- std::vector<std::string> &buffer_constructor,
+ const FieldDef &field, std::vector<std::string> &buffer_constructor,
std::vector<std::string> &base_constructor,
const std::string &indentation) {
- auto vectortype = field.value.type.VectorType();
+ const auto vectortype = field.value.type.VectorType();
+ const auto field_var = namer_.Field(field);
+ const auto field_field = namer_.Field(field);
if (vectortype.base_type != BASE_TYPE_UTYPE) {
- buffer_constructor.push_back(name + " = []");
- buffer_constructor.push_back("for index in 0..<_t." + name + "Count {");
- base_constructor.push_back(name + " = []");
+ buffer_constructor.push_back(field_var + " = []");
+ buffer_constructor.push_back("for index in 0..<_t." + field_field +
+ "Count {");
+ base_constructor.push_back(field_var + " = []");
}
switch (vectortype.base_type) {
case BASE_TYPE_STRUCT: {
code_.SetValue("VALUETYPE", GenType(vectortype, true));
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: [{{VALUETYPE}}?]";
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: [{{VALUETYPE}}?]";
if (!vectortype.struct_def->fixed) {
- buffer_constructor.push_back(indentation + "var __v_ = _t." + name +
- "(at: index)");
- buffer_constructor.push_back(indentation + name +
+ buffer_constructor.push_back(indentation + "var __v_ = _t." +
+ field_field + "(at: index)");
+ buffer_constructor.push_back(indentation + field_var +
".append(__v_?.unpack())");
} else {
- buffer_constructor.push_back(indentation + name + ".append(_t." +
- name + "(at: index))");
+ buffer_constructor.push_back(indentation + field_var + ".append(_t." +
+ field_var + "(at: index))");
}
break;
}
@@ -1619,7 +1661,7 @@
break;
}
case BASE_TYPE_UNION: {
- BuildUnionEnumSwitchCase(*field.value.type.enum_def, name,
+ BuildUnionEnumSwitchCase(*field.value.type.enum_def, field_var,
buffer_constructor, indentation, true);
break;
}
@@ -1628,18 +1670,18 @@
code_.SetValue(
"VALUETYPE",
(IsString(vectortype) ? "String?" : GenType(vectortype)));
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: [{{VALUETYPE}}]";
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: [{{VALUETYPE}}]";
if (IsEnum(vectortype) && vectortype.base_type != BASE_TYPE_UNION) {
- auto default_value = IsEnum(field.value.type)
- ? GenEnumDefaultValue(field)
- : field.value.constant;
- buffer_constructor.push_back(indentation + name + ".append(_t." +
- name + "(at: index)!)");
+ const auto default_value = IsEnum(field.value.type)
+ ? GenEnumDefaultValue(field)
+ : field.value.constant;
+ buffer_constructor.push_back(indentation + field_var + ".append(_t." +
+ field_field + "(at: index)!)");
break;
}
- buffer_constructor.push_back(indentation + name + ".append(_t." + name +
- "(at: index))");
+ buffer_constructor.push_back(indentation + field_var + ".append(_t." +
+ field_field + "(at: index))");
break;
}
}
@@ -1647,19 +1689,17 @@
buffer_constructor.push_back("}");
}
- void BuildUnionEnumSwitchCaseWritter(const EnumDef &ev) {
- auto field_name = Name(ev);
- code_.SetValue("VALUETYPE", field_name);
+ void BuildUnionEnumSwitchCaseWritter(const EnumDef &ed) {
code_ += "switch type {";
- for (auto it = ev.Vals().begin(); it < ev.Vals().end(); ++it) {
- auto field = **it;
- auto ev_name = Name(field);
- auto type = GenType(field.union_type);
- auto is_struct = IsStruct(field.union_type) ? type + Mutable() : type;
- if (field.union_type.base_type == BASE_TYPE_NONE) { continue; }
- code_ += "case ." + ev_name + ":";
+ for (auto it = ed.Vals().begin(); it < ed.Vals().end(); ++it) {
+ const auto ev = **it;
+ const auto variant = namer_.LegacySwiftVariant(ev);
+ const auto type = GenType(ev.union_type);
+ const auto is_struct = IsStruct(ev.union_type) ? type + Mutable() : type;
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ code_ += "case ." + variant + ":";
Indent();
- code_ += "var __obj = value as? " + GenType(field.union_type, true);
+ code_ += "var __obj = value as? " + GenType(ev.union_type, true);
code_ += "return " + is_struct + ".pack(&builder, obj: &__obj)";
Outdent();
}
@@ -1667,34 +1707,34 @@
code_ += "}";
}
- void BuildUnionEnumSwitchCase(const EnumDef &ev, const std::string &name,
+ void BuildUnionEnumSwitchCase(const EnumDef &ed, const std::string &field,
std::vector<std::string> &buffer_constructor,
const std::string &indentation = "",
const bool is_vector = false) {
- auto field_name = NameWrappedInNameSpace(ev);
- code_.SetValue("VALUETYPE", field_name);
- code_ += "{{ACCESS_TYPE}} var {{VALUENAME}}: \\";
+ const auto ns_type = namer_.NamespacedType(ed);
+ code_.SetValue("VALUETYPE", ns_type);
+ code_ += "{{ACCESS_TYPE}} var {{FIELDVAR}}: \\";
code_ += is_vector ? "[{{VALUETYPE}}Union?]" : "{{VALUETYPE}}Union?";
- auto vector_reader = is_vector ? "(at: index" : "";
- buffer_constructor.push_back(indentation + "switch _t." + name + "Type" +
+ const auto vector_reader = is_vector ? "(at: index" : "";
+ buffer_constructor.push_back(indentation + "switch _t." + field + "Type" +
vector_reader + (is_vector ? ")" : "") + " {");
- for (auto it = ev.Vals().begin(); it < ev.Vals().end(); ++it) {
- auto field = **it;
- auto ev_name = Name(field);
- if (field.union_type.base_type == BASE_TYPE_NONE) { continue; }
- auto type = IsStruct(field.union_type)
- ? GenType(field.union_type) + Mutable()
- : GenType(field.union_type);
- buffer_constructor.push_back(indentation + "case ." + ev_name + ":");
+ for (auto it = ed.Vals().begin(); it < ed.Vals().end(); ++it) {
+ const auto ev = **it;
+ const auto variant = namer_.LegacySwiftVariant(ev);
+ if (ev.union_type.base_type == BASE_TYPE_NONE) { continue; }
+ const auto type = IsStruct(ev.union_type)
+ ? GenType(ev.union_type) + Mutable()
+ : GenType(ev.union_type);
+ buffer_constructor.push_back(indentation + "case ." + variant + ":");
buffer_constructor.push_back(
- indentation + " var _v = _t." + name + (is_vector ? "" : "(") +
+ indentation + " var _v = _t." + field + (is_vector ? "" : "(") +
vector_reader + (is_vector ? ", " : "") + "type: " + type + ".self)");
- auto constructor =
- field_name + "Union(_v?.unpack(), type: ." + ev_name + ")";
+ const auto constructor =
+ ns_type + "Union(_v?.unpack(), type: ." + variant + ")";
buffer_constructor.push_back(
- indentation + " " + name +
+ indentation + " " + field +
(is_vector ? ".append(" + constructor + ")" : " = " + constructor));
}
buffer_constructor.push_back(indentation + "default: break");
@@ -1702,13 +1742,14 @@
}
void AddMinOrMaxEnumValue(const std::string &str, const std::string &type) {
- auto current_value = str;
+ const auto current_value = str;
code_.SetValue(type, current_value);
code_ += "{{ACCESS_TYPE}} static var " + type +
": {{ENUM_NAME}} { return .{{" + type + "}} }";
}
- void GenLookup(const FieldDef &key_field) {
+ void GenLookup(const FieldDef &key_field, const std::string &struct_type) {
+ code_.SetValue("STRUCTTYPE", struct_type);
code_.SetValue("OFFSET", NumToString(key_field.value.offset));
std::string offset_reader =
"Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: {{OFFSET}}, "
@@ -1718,7 +1759,7 @@
code_ +=
"fileprivate static func lookupByKey(vector: Int32, key: {{TYPE}}, "
"fbb: "
- "ByteBuffer) -> {{VALUENAME}}? {";
+ "ByteBuffer) -> {{STRUCTTYPE}}? {";
Indent();
if (IsString(key_field.value.type))
code_ += "let key = key.utf8.map { $0 }";
@@ -1748,7 +1789,7 @@
Outdent();
code_ += "} else {";
Indent();
- code_ += "return {{VALUENAME}}(fbb, o: tableOffset)";
+ code_ += "return {{STRUCTTYPE}}(fbb, o: tableOffset)";
Outdent();
code_ += "}";
Outdent();
@@ -1762,7 +1803,7 @@
if (field.padding) {
for (int i = 0; i < 4; i++) {
if (static_cast<int>(field.padding) & (1 << i)) {
- auto bits = (1 << i) * 8;
+ const auto bits = (1 << i) * 8;
code_ += "private let padding" + NumToString((*id)++) + "__: UInt" +
NumToString(bits) + " = 0";
}
@@ -1784,8 +1825,7 @@
}
std::string GenReaderMainBody(const std::string &optional = "") {
- return "{{ACCESS_TYPE}} var {{VALUENAME}}: {{VALUETYPE}}" + optional +
- " { ";
+ return "{{ACCESS_TYPE}} var {{FIELDVAR}}: {{VALUETYPE}}" + optional + " { ";
}
std::string GenReader(const std::string &type,
@@ -1799,36 +1839,33 @@
std::string GenMutate(const std::string &offset,
const std::string &get_offset, bool isRaw = false) {
- return "@discardableResult {{ACCESS_TYPE}} func mutate({{VALUENAME}}: "
+ return "@discardableResult {{ACCESS_TYPE}} func mutate({{FIELDVAR}}: "
"{{VALUETYPE}}) -> Bool {" +
- get_offset + " return {{ACCESS}}.mutate({{VALUENAME}}" +
+ get_offset + " return {{ACCESS}}.mutate({{FIELDVAR}}" +
(isRaw ? ".rawValue" : "") + ", index: " + offset + ") }";
}
std::string GenMutateArray() {
- return "{{ACCESS_TYPE}} func mutate({{VALUENAME}}: {{VALUETYPE}}, at "
- "index: "
- "Int32) -> Bool { " +
+ return "{{ACCESS_TYPE}} func mutate({{FIELDVAR}}: {{VALUETYPE}}, at "
+ "index: Int32) -> Bool { " +
GenOffset() +
- "return {{ACCESS}}.directMutate({{VALUENAME}}, index: "
+ "return {{ACCESS}}.directMutate({{FIELDVAR}}, index: "
"{{ACCESS}}.vector(at: o) + index * {{SIZE}}) }";
}
std::string GenEnumDefaultValue(const FieldDef &field) {
- auto &value = field.value;
+ const auto &value = field.value;
FLATBUFFERS_ASSERT(value.type.enum_def);
- auto &enum_def = *value.type.enum_def;
+ const auto &enum_def = *value.type.enum_def;
// Vector of enum defaults are always "[]" which never works.
const std::string constant = IsVector(value.type) ? "0" : value.constant;
- auto enum_val = enum_def.FindByValue(constant);
- std::string name;
+ const auto enum_val = enum_def.FindByValue(constant);
if (enum_val) {
- name = Name(*enum_val);
+ return "." + namer_.LegacySwiftVariant(*enum_val);
} else {
const auto &ev = **enum_def.Vals().begin();
- name = Name(ev);
+ return "." + namer_.LegacySwiftVariant(ev);
}
- return "." + name;
}
std::string GenEnumConstructor(const std::string &at) {
@@ -1836,15 +1873,14 @@
}
std::string ValidateFunc() {
- return "static func validateVersion() { FlatBuffersVersion_2_0_0() }";
+ return "static func validateVersion() { FlatBuffersVersion_2_0_8() }";
}
std::string GenType(const Type &type,
const bool should_consider_suffix = false) const {
- return IsScalar(type.base_type)
- ? GenTypeBasic(type)
- : (IsArray(type) ? GenType(type.VectorType())
- : GenTypePointer(type, should_consider_suffix));
+ return IsScalar(type.base_type) ? GenTypeBasic(type)
+ : IsArray(type) ? GenType(type.VectorType())
+ : GenTypePointer(type, should_consider_suffix);
}
std::string GenTypePointer(const Type &type,
@@ -1853,12 +1889,11 @@
case BASE_TYPE_STRING: return "String";
case BASE_TYPE_VECTOR: return GenType(type.VectorType());
case BASE_TYPE_STRUCT: {
- auto &struct_ = *type.struct_def;
- if (should_consider_suffix && !struct_.fixed) {
- return WrapInNameSpace(struct_.defined_namespace,
- ObjectAPIName(Name(struct_)));
+ const auto &sd = *type.struct_def;
+ if (should_consider_suffix && !sd.fixed) {
+ return namer_.NamespacedObjectType(sd);
}
- return WrapInNameSpace(struct_.defined_namespace, Name(struct_));
+ return namer_.NamespacedType(sd);
}
case BASE_TYPE_UNION:
default: return "FlatbuffersInitializable";
@@ -1869,22 +1904,10 @@
return GenTypeBasic(type, true);
}
- std::string ObjectAPIName(const std::string &name) const {
- return parser_.opts.object_prefix + name + parser_.opts.object_suffix;
- }
-
void Indent() { code_.IncrementIdentLevel(); }
void Outdent() { code_.DecrementIdentLevel(); }
- std::string NameWrappedInNameSpace(const EnumDef &enum_def) const {
- return WrapInNameSpace(enum_def.defined_namespace, Name(enum_def));
- }
-
- std::string NameWrappedInNameSpace(const StructDef &struct_def) const {
- return WrapInNameSpace(struct_def.defined_namespace, Name(struct_def));
- }
-
std::string GenTypeBasic(const Type &type, bool can_override) const {
// clang-format off
static const char * const swift_type[] = {
@@ -1896,29 +1919,15 @@
};
// clang-format on
if (can_override) {
- if (type.enum_def) return NameWrappedInNameSpace(*type.enum_def);
+ if (type.enum_def) return namer_.NamespacedType(*type.enum_def);
if (type.base_type == BASE_TYPE_BOOL) return "Bool";
}
return swift_type[static_cast<int>(type.base_type)];
}
- std::string EscapeKeyword(const std::string &name) const {
- return keywords_.find(name) == keywords_.end() ? name : name + "_";
- }
-
std::string Mutable() const { return "_Mutable"; }
- std::string Name(const EnumVal &ev) const {
- auto name = ev.name;
- if (isupper(name.front())) {
- std::transform(name.begin(), name.end(), name.begin(), CharToLower);
- }
- return EscapeKeyword(ConvertCase(name, Case::kLowerCamel));
- }
-
- std::string Name(const Definition &def) const {
- return EscapeKeyword(ConvertCase(def.name, Case::kLowerCamel));
- }
+ IdlNamer namer_;
};
} // namespace swift
bool GenerateSwift(const Parser &parser, const std::string &path,