From 8468eab83bacc8bbd6cb5ae22197af06a9437b2d Mon Sep 17 00:00:00 2001 From: Casper Date: Sun, 13 Mar 2022 18:46:27 -0400 Subject: [PATCH] Namersw (#7167) * Define and use Namer overloads * more * NamespacedType needs a public string-like overload * Move Rust FieldOffsetName to Namer LegacyRustFieldOffsetName * Started swift * More Namer updates * Remove more usage of the variable 'name' which was semantically overloaded * unshadow varible * Make ptr to bool explicit Co-authored-by: Casper Neo --- src/idl_gen_go.cpp | 1 + src/idl_gen_python.cpp | 1 + src/idl_gen_rust.cpp | 1 + src/idl_gen_swift.cpp | 856 +++++++++++++++++++---------------------- src/namer.h | 56 ++- 5 files changed, 434 insertions(+), 481 deletions(-) diff --git a/src/idl_gen_go.cpp b/src/idl_gen_go.cpp index 5f352df84..0eebbaf24 100644 --- a/src/idl_gen_go.cpp +++ b/src/idl_gen_go.cpp @@ -61,6 +61,7 @@ Namer::Config GoDefaultConfig() { /*variables=*/Case::kLowerCamel, /*variants=*/Case::kKeep, /*enum_variant_seperator=*/"", // I.e. Concatenate. + /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase, /*namespaces=*/Case::kKeep, /*namespace_seperator=*/"__", /*object_prefix=*/"", diff --git a/src/idl_gen_python.cpp b/src/idl_gen_python.cpp index 99ba48c9a..b319ed64d 100644 --- a/src/idl_gen_python.cpp +++ b/src/idl_gen_python.cpp @@ -49,6 +49,7 @@ Namer::Config PythonDefaultConfig() { /*variable=*/Case::kLowerCamel, /*variants=*/Case::kKeep, /*enum_variant_seperator=*/".", + /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase, /*namespaces=*/Case::kKeep, // Packages in python. /*namespace_seperator=*/".", /*object_prefix=*/"", diff --git a/src/idl_gen_rust.cpp b/src/idl_gen_rust.cpp index d39ab68b2..9d4eac095 100644 --- a/src/idl_gen_rust.cpp +++ b/src/idl_gen_rust.cpp @@ -37,6 +37,7 @@ Namer::Config RustDefaultConfig() { /*variables=*/Case::kUnknown, // Unused. /*variants=*/Case::kKeep, /*enum_variant_seperator=*/"::", + /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase, /*namespaces=*/Case::kSnake, /*namespace_seperator=*/"::", /*object_prefix=*/"", diff --git a/src/idl_gen_swift.cpp b/src/idl_gen_swift.cpp index c3c322fca..794a970f5 100644 --- a/src/idl_gen_swift.cpp +++ b/src/idl_gen_swift.cpp @@ -21,17 +21,58 @@ #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" +#include "namer.h" namespace flatbuffers { namespace swift { +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" }; +} + +std::set 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", + }; +} + + inline 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) -> " + return "{{ACCESS_TYPE}} func {{FIELDMETHOD}}(at index: Int32) -> " "{{VALUETYPE}}" + optional + " { "; } @@ -45,92 +86,11 @@ class SwiftGenerator : public BaseGenerator { 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_(SwiftDefaultConfig().WithFlagOptions(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() { @@ -183,10 +143,11 @@ class SwiftGenerator : public BaseGenerator { // 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 = + 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 +164,14 @@ class SwiftGenerator : public BaseGenerator { 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 +179,19 @@ class SwiftGenerator : public BaseGenerator { 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,18 +203,16 @@ class SwiftGenerator : public BaseGenerator { 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_ += ""; @@ -275,22 +235,21 @@ class SwiftGenerator : public BaseGenerator { 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 +262,11 @@ class SwiftGenerator : public BaseGenerator { 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 +290,7 @@ class SwiftGenerator : public BaseGenerator { } 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 +301,11 @@ class SwiftGenerator : public BaseGenerator { // 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 = + 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 +335,7 @@ class SwiftGenerator : public BaseGenerator { 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 +343,15 @@ class SwiftGenerator : public BaseGenerator { *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; @@ -400,7 +360,7 @@ class SwiftGenerator : public BaseGenerator { continue; } code += - nameprefix + name + ": " + obj_api_named + object_name + "." + name; + nameprefix + field_var + ": " + obj_api_named + object_name + "." + field_field; code += ", "; } } @@ -410,7 +370,8 @@ class SwiftGenerator : public BaseGenerator { // 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 = + struct_def.attributes.Lookup("private") != nullptr; code_.SetValue("ACCESS_TYPE", is_private_access ? "internal" : "public"); GenObjectHeader(struct_def); GenTableAccessors(struct_def); @@ -435,7 +396,7 @@ class SwiftGenerator : public BaseGenerator { 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 +411,8 @@ class SwiftGenerator : public BaseGenerator { 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_ += @@ -495,7 +456,7 @@ class SwiftGenerator : public BaseGenerator { std::vector require_fields; std::vector create_func_body; std::vector 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 +516,12 @@ class SwiftGenerator : public BaseGenerator { 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.name) + + "(offsets:[Offset], " + "_ fbb: inout FlatBufferBuilder) -> Offset {"; Indent(); code_ += spacing + "var off = offsets"; code_ += @@ -573,7 +532,7 @@ class SwiftGenerator : public BaseGenerator { code_ += spacing + "return fbb.createVector(ofOffsets: off)"; Outdent(); code_ += "}"; - GenLookup(*key_field); + GenLookup(*key_field, namer_.NamespacedType(struct_def)); } } @@ -583,42 +542,44 @@ class SwiftGenerator : public BaseGenerator { 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 +590,48 @@ class SwiftGenerator : public BaseGenerator { 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 + "? = 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 + ": " + + create_func_header.push_back(arg_label + " " + field_var + ": " + "Offset = Offset()"); - auto reader_type = + 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_ += "public static func " + + namer_.Method("start_vector_of_" + field_var) + "(_ size: Int, in builder: inout " "FlatBufferBuilder) {"; Indent(); @@ -685,25 +646,26 @@ class SwiftGenerator : public BaseGenerator { 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 +690,7 @@ class SwiftGenerator : public BaseGenerator { } 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 +701,15 @@ class SwiftGenerator : public BaseGenerator { 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 +726,12 @@ class SwiftGenerator : public BaseGenerator { 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 +742,7 @@ class SwiftGenerator : public BaseGenerator { case BASE_TYPE_UNION: code_.SetValue("CONSTANT", "nil"); code_ += - "{{ACCESS_TYPE}} func {{VALUENAME}}(type: " "T.Type) -> T" + is_required + " { " + GenOffset() + required_reader + @@ -793,20 +754,19 @@ class SwiftGenerator : public BaseGenerator { 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_ += "{{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}}(at " + "{{ACCESS_TYPE}} func {{FIELDVAR}}(at " "index: " "Int32, type: T.Type) -> T? { " + GenOffset() + "\\"; @@ -825,7 +785,7 @@ class SwiftGenerator : public BaseGenerator { "{{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 +796,7 @@ class SwiftGenerator : public BaseGenerator { 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.name)); code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable()); code_ += GenArrayMainBody(nullable) + GenOffset() + const_string + GenConstructor("{{ACCESS}}.vector(at: o) + index * {{SIZE}}"); @@ -872,10 +831,10 @@ class SwiftGenerator : public BaseGenerator { 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 +848,12 @@ class SwiftGenerator : public BaseGenerator { 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 +861,8 @@ class SwiftGenerator : public BaseGenerator { 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 +870,25 @@ class SwiftGenerator : public BaseGenerator { 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 +899,18 @@ class SwiftGenerator : public BaseGenerator { 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 +921,31 @@ class SwiftGenerator : public BaseGenerator { 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 +958,17 @@ class SwiftGenerator : public BaseGenerator { 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(); @@ -1052,14 +1003,13 @@ class SwiftGenerator : public BaseGenerator { 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 +1019,7 @@ class SwiftGenerator : public BaseGenerator { code_ += "try _v.visit(field: {{TABLEOFFSET}}.{{OFFSET}}.p, fieldName: " - "\"{{VALUENAME}}\", required: {{ISREQUIRED}}, type: " + "\"{{FIELDVAR}}\", required: {{ISREQUIRED}}, type: " "{{VALUETYPE}}.self)"; } code_ += "_v.finish()"; @@ -1078,28 +1028,27 @@ class SwiftGenerator : public BaseGenerator { } 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 +1074,11 @@ class SwiftGenerator : public BaseGenerator { } 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>"; @@ -1139,7 +1088,7 @@ class SwiftGenerator : public BaseGenerator { } 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 +1102,7 @@ class SwiftGenerator : public BaseGenerator { 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 +1111,11 @@ class SwiftGenerator : public BaseGenerator { 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 +1138,14 @@ class SwiftGenerator : public BaseGenerator { "{{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 +1183,7 @@ class SwiftGenerator : public BaseGenerator { 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 +1196,18 @@ class SwiftGenerator : public BaseGenerator { // 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 +1218,7 @@ class SwiftGenerator : public BaseGenerator { "{{ACCESS_TYPE}} static func pack(_ builder: inout FlatBufferBuilder, " "obj: " "inout " + - name + ") -> Offset {"; + type_name + ") -> Offset {"; Indent(); } @@ -1281,40 +1228,39 @@ class SwiftGenerator : public BaseGenerator { 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 buffer_constructor; std::vector 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 +1272,37 @@ class SwiftGenerator : public BaseGenerator { } void GenerateObjectAPITableExtension(const StructDef &struct_def) { - GenerateObjectAPIExtensionHeader(ObjectAPIName("{{STRUCTNAME}}")); + GenerateObjectAPIExtensionHeader(namer_.NamespacedObjectType(struct_def)); std::vector 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 +1316,31 @@ class SwiftGenerator : public BaseGenerator { 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 +1353,79 @@ class SwiftGenerator : public BaseGenerator { 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 +1445,125 @@ class SwiftGenerator : public BaseGenerator { const FieldDef &field, bool is_fixed, std::vector &buffer_constructor, std::vector &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 &buffer_constructor, + const FieldDef &field, std::vector &buffer_constructor, std::vector &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 +1572,7 @@ class SwiftGenerator : public BaseGenerator { 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 +1581,18 @@ class SwiftGenerator : public BaseGenerator { 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 +1600,17 @@ class SwiftGenerator : public BaseGenerator { 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 +1618,34 @@ class SwiftGenerator : public BaseGenerator { code_ += "}"; } - void BuildUnionEnumSwitchCase(const EnumDef &ev, const std::string &name, + void BuildUnionEnumSwitchCase(const EnumDef &ed, const std::string &field, std::vector &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 +1653,14 @@ class SwiftGenerator : public BaseGenerator { } 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 +1670,7 @@ class SwiftGenerator : public BaseGenerator { 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 +1700,7 @@ class SwiftGenerator : public BaseGenerator { Outdent(); code_ += "} else {"; Indent(); - code_ += "return {{VALUENAME}}(fbb, o: tableOffset)"; + code_ += "return {{STRUCTTYPE}}(fbb, o: tableOffset)"; Outdent(); code_ += "}"; Outdent(); @@ -1762,7 +1714,7 @@ class SwiftGenerator : public BaseGenerator { if (field.padding) { for (int i = 0; i < 4; i++) { if (static_cast(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 +1736,7 @@ class SwiftGenerator : public BaseGenerator { } 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 +1750,33 @@ class SwiftGenerator : public BaseGenerator { 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) { @@ -1841,10 +1789,9 @@ class SwiftGenerator : public BaseGenerator { 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 +1800,11 @@ class SwiftGenerator : public BaseGenerator { 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 +1815,10 @@ class SwiftGenerator : public BaseGenerator { 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 +1830,15 @@ class SwiftGenerator : public BaseGenerator { }; // 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(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)); - } + Namer namer_; }; } // namespace swift bool GenerateSwift(const Parser &parser, const std::string &path, diff --git a/src/namer.h b/src/namer.h index 9ba5451f2..6cf97846d 100644 --- a/src/namer.h +++ b/src/namer.h @@ -62,6 +62,16 @@ class Namer { // e.g. `Enum::MyVariant` uses `::`. std::string enum_variant_seperator; + // Configures, when formatting code, whether symbols are checked against + // keywords and escaped before or after case conversion. It does not make + // sense to do so before, but its legacy behavior. :shrug: + // TODO(caspern): Deprecate. + enum class Escape { + BeforeConvertingCase, + AfterConvertingCase, + }; + Escape escape_keywords; + // Namespaces // e.g. `namespace my_namespace {}` @@ -115,7 +125,6 @@ class Namer { // Types are always structs or enums so we can only expose these two // overloads. std::string Type(const StructDef &d) const { return Type(d.name); } - std::string Type(const EnumDef &d) const { return Type(d.name); } template std::string Method(const T &s) const { @@ -142,6 +151,10 @@ class Namer { std::string Variable(const StructDef &s) const { return Variable(s.name); } + std::string Variable(const std::string &s) const { + return Format(s, config_.variables); + } + std::string Variant(const EnumVal &s) const { return Variant(s.name); } std::string EnumVariant(const EnumDef &e, const EnumVal &v) const { @@ -171,15 +184,17 @@ class Namer { } std::string NamespacedType(const Definition &def) const { - if (def.defined_namespace != nullptr) { - return NamespacedType(def.defined_namespace->components, def.name); - } - return Type(def.name); + return NamespacedString(def.defined_namespace, Type(def.name)); } std::string NamespacedType(const std::vector &ns, const std::string &s) const { - return Namespace(ns) + config_.namespace_seperator + Type(s); + return (ns.empty() ? "" : (Namespace(ns) + config_.namespace_seperator)) + + Type(s); + } + + std::string NamespacedObjectType(const Definition &def) const { + return NamespacedString(def.defined_namespace, ObjectType(def.name)); } // Returns `filename` with the right casing, suffix, and extension. @@ -240,6 +255,15 @@ class Namer { return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper); } + // TODO(caspern): What's up with this case style? + std::string LegacySwiftVariant(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)); + } + private: std::string Type(const std::string &s) const { return Format(s, config_.types); @@ -253,18 +277,24 @@ class Namer { return Format(s, config_.fields); } - std::string Variable(const std::string &s) const { - return Format(s, config_.variables); - } - std::string Variant(const std::string &s) const { return Format(s, config_.variants); } + std::string NamespacedString(const struct Namespace *ns, + const std::string &str) const { + std::string ret; + if (ns != nullptr) { ret += Namespace(ns->components); } + if (!ret.empty()) ret += config_.namespace_seperator; + return ret + str; + } + std::string Format(const std::string &s, Case casing) const { - // NOTE: If you need to escape keywords after converting case, which would - // make more sense than this, make it a config option. - return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel); + if (config_.escape_keywords == Config::Escape::BeforeConvertingCase) { + return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel); + } else { + return EscapeKeyword(ConvertCase(s, casing, Case::kLowerCamel)); + } } const Config config_; const std::set keywords_;