From 1cf534d7925514f436c8198f9821c84e3e9f3500 Mon Sep 17 00:00:00 2001 From: Alexey Khokhlov Date: Fri, 31 Oct 2014 20:42:20 +0300 Subject: [PATCH] Performance improvements when serialize/deserialize big data --- README.md | 2 + .../xcschemes/ProtocolBuffers.xcscheme | 96 + .../runtime-pb-swift/CodedInputStream.swift | 43 +- .../runtime-pb-swift/CodedOutputStream.swift | 20 +- .../runtime-pb-swift/RingBuffer.swift | 19 +- .../ProtocolBuffersTests/Perfomance.pb.swift | 44 +- .../ProtocolBuffersTests/Perfomance.proto | 3 +- .../ProtocolBuffersTests.swift | 1 + src/compiler/main.cc | 6 +- src/compiler/swift_enum.cc | 132 +- src/compiler/swift_enum.h | 66 +- src/compiler/swift_enum_field.cc | 644 ++++--- src/compiler/swift_enum_field.h | 126 +- src/compiler/swift_extension.cc | 315 ++-- src/compiler/swift_extension.h | 62 +- src/compiler/swift_field.cc | 105 +- src/compiler/swift_field.h | 110 +- src/compiler/swift_file.cc | 292 +-- src/compiler/swift_file.h | 60 +- src/compiler/swift_generator.cc | 76 +- src/compiler/swift_generator.h | 40 +- src/compiler/swift_helpers.cc | 930 +++++----- src/compiler/swift_helpers.h | 226 +-- src/compiler/swift_message.cc | 1612 ++++++++--------- src/compiler/swift_message.h | 126 +- src/compiler/swift_message_field.cc | 642 +++---- src/compiler/swift_message_field.h | 124 +- src/compiler/swift_oneof.cc | 206 +-- src/compiler/swift_oneof.h | 52 +- src/compiler/swift_primitive_field.cc | 912 +++++----- src/compiler/swift_primitive_field.h | 116 +- 31 files changed, 3671 insertions(+), 3537 deletions(-) create mode 100644 src/ProtocolBuffers/ProtocolBuffers.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme diff --git a/README.md b/README.md index 3ce472d..60e4c64 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ #Protocol Buffers for Swift +[![Platform](http://img.shields.io/badge/platform-ios%20%7C%20osx-green.svg)](https://github.com/alexeyxo/protobuf-swift) +[![Release](http://img.shields.io/github/tag/alexeyxo/protobuf-swift.svg)](https://github.com/alexeyxo/protobuf-swift/releases/tag/v1.0) An implementation of Protocol Buffers in Swift. diff --git a/src/ProtocolBuffers/ProtocolBuffers.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme b/src/ProtocolBuffers/ProtocolBuffers.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme new file mode 100644 index 0000000..2c87df8 --- /dev/null +++ b/src/ProtocolBuffers/ProtocolBuffers.xcodeproj/xcshareddata/xcschemes/ProtocolBuffers.xcscheme @@ -0,0 +1,96 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/CodedInputStream.swift b/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/CodedInputStream.swift index 1843247..8f75a4c 100644 --- a/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/CodedInputStream.swift +++ b/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/CodedInputStream.swift @@ -25,7 +25,7 @@ let BUFFER_SIZE:Int32 = 4096; public class CodedInputStream { - public var buffer:[Byte]! + public var buffer:[Byte] private var input:NSInputStream! private var bufferSize:Int32 = 0 private var bufferSizeAfterLimit:Int32 = 0 @@ -39,7 +39,7 @@ public class CodedInputStream public init (data aData:[Byte]) { buffer = aData - bufferSize = Int32(buffer!.count) + bufferSize = Int32(buffer.count) currentLimit = INT_MAX recursionLimit = DEFAULT_RECURSION_LIMIT sizeLimit = DEFAULT_SIZE_LIMIT @@ -87,7 +87,7 @@ public class CodedInputStream if input != nil { - bufferSize = Int32(input!.read(&buffer!, maxLength:buffer!.count)) + bufferSize = Int32(input!.read(&buffer, maxLength:buffer.count)) } @@ -131,8 +131,9 @@ public class CodedInputStream if (size <= bufferSize - bufferPos) { - var data = [Byte](count: buffer!.count - Int(bufferPos), repeatedValue: 0) - data[0...data.count-1] = buffer![Int(bufferPos)...Int(buffer!.count-1)] + var data = [Byte](count: buffer.count - Int(bufferPos), repeatedValue: 0) +// data[0...data.count-1] = buffer![Int(bufferPos)...Int(buffer!.count-1)] + memcpy(&data, &buffer + Int(bufferPos), UInt(buffer.count - Int(bufferPos))) bufferPos += size; return data; } @@ -140,21 +141,23 @@ public class CodedInputStream var bytes = [Byte](count:Int(size), repeatedValue: 0) var pos:Int32 = bufferSize - bufferPos; - bytes[0...bytes.count-1] = buffer![Int(bufferPos)...Int(buffer!.count-1)] +// bytes[0...bytes.count-1] = buffer![Int(bufferPos)...Int(buffer!.count-1)] + memcpy(&bytes, &buffer + Int(bufferPos), UInt(pos)) bufferPos = bufferSize; refillBuffer(true) while (size - pos > bufferSize) { - - bytes[Int(pos)...Int(bufferSize)] = buffer![0...Int(bufferSize)] + memcpy(&bytes + Int(pos), &buffer, UInt(bufferSize)) +// bytes[Int(pos)...Int(bufferSize)] = buffer![0...Int(bufferSize)] pos += bufferSize bufferPos = bufferSize refillBuffer(true) } - bytes[Int(pos)...Int(bufferSize)] = buffer![0...Int(size - pos)] +// bytes[Int(pos)...Int(bufferSize)] = buffer![0...Int(size - pos)] + memcpy(&bytes + Int(pos), &buffer, UInt(size - pos)) bufferPos = size - pos; return bytes @@ -198,11 +201,12 @@ public class CodedInputStream var bytes:[Byte] = [Byte](count: Int(size), repeatedValue: 0) var pos:Int = originalBufferSize - originalBufferPos; - bytes[0...bytes.count-1] = buffer![Int(originalBufferSize)...Int(pos)] - +// bytes[0...bytes.count-1] = buffer[Int(originalBufferSize)...Int(pos)] + memcpy(&bytes, &buffer + Int(originalBufferPos), UInt(pos)) for chunk in chunks { - bytes[Int(pos).. 0) { - - var data = buffer[Int(bufferPos).. 0) { - var result:[Byte] = [Byte](count: Int(size), repeatedValue: 0) - result[0.. 0) + while (length > 0) { - var written:Int32 = buffer.appendData(data, offset: aOffset, length: aLength) - aOffset += Int32(written) - aLength -= Int32(written) - if (written == 0 && aLength > 0) + var written:Int32 = buffer.appendData(data, offset: offset, length: length) + offset += Int32(written) + length -= Int32(written) + if (written == 0 || length > 0) { flush() } @@ -237,13 +237,13 @@ public class CodedOutputStream writeMessageNoTag(value) } - public func writeDataNoTag(data:[Byte]?) + public func writeDataNoTag(data:[Byte]) { - writeRawVarint32(Int32(data!.count)) - writeRawData(data!) + writeRawVarint32(Int32(data.count)) + writeRawData(data) } - public func writeData(fieldNumber:Int32, value:[Byte]?) + public func writeData(fieldNumber:Int32, value:[Byte]) { writeTag(fieldNumber, format: WireFormat.WireFormatLengthDelimited) writeDataNoTag(value) diff --git a/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/RingBuffer.swift b/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/RingBuffer.swift index 1803f00..391bfcb 100644 --- a/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/RingBuffer.swift +++ b/src/ProtocolBuffers/ProtocolBuffers/runtime-pb-swift/RingBuffer.swift @@ -57,19 +57,17 @@ internal class RingBuffer return true } - func appendData(data:[Byte], var offset:Int32, var length:Int32) -> Int32 + func appendData(var input:[Byte], var offset:Int32, var length:Int32) -> Int32 { var totalWritten:Int32 = 0 - if (position >= tail) { totalWritten = min(Int32(buffer.count) - Int32(position), Int32(length)) - var subdata = data[Int(offset).. position { - var written:Int = stream.write(&data, maxLength:Int(buffer.count - Int(tail))) + var written:Int = stream.write(&data + Int(tail), maxLength:Int(buffer.count - Int(tail))) if written <= 0 { return totalWritten @@ -119,7 +114,7 @@ internal class RingBuffer if (tail < position) { - var written:Int = stream.write(&data, maxLength:Int(position - tail)) + var written:Int = stream.write(&data + Int(tail), maxLength:Int(position - tail)) if (written <= 0) { return totalWritten diff --git a/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.pb.swift b/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.pb.swift index ba186c1..9689099 100644 --- a/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.pb.swift +++ b/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.pb.swift @@ -30,6 +30,7 @@ func == (lhs: Perfomance, rhs: Perfomance) -> Bool { fieldCheck = fieldCheck && (lhs.hasDoubles == rhs.hasDoubles) && (!lhs.hasDoubles || lhs.doubles == rhs.doubles) fieldCheck = fieldCheck && (lhs.hasFloats == rhs.hasFloats) && (!lhs.hasFloats || lhs.floats == rhs.floats) fieldCheck = fieldCheck && (lhs.hasStr == rhs.hasStr) && (!lhs.hasStr || lhs.str == rhs.str) + fieldCheck = fieldCheck && (lhs.hasBytes == rhs.hasBytes) && (!lhs.hasBytes || lhs.bytes == rhs.bytes) return (fieldCheck && (lhs.unknownFields == rhs.unknownFields)) } @@ -49,6 +50,9 @@ final public class Perfomance : GeneratedMessage { private(set) var hasStr:Bool = false private(set) var str:String = "" + private(set) var hasBytes:Bool = false + private(set) var bytes:Array = [Byte]() + required public init() { super.init() } @@ -65,9 +69,6 @@ final public class Perfomance : GeneratedMessage { if !hasFloats { return false } - if !hasStr { - return false - } return true } override public func writeToCodedOutputStream(output:CodedOutputStream) { @@ -86,6 +87,9 @@ final public class Perfomance : GeneratedMessage { if hasStr { output.writeString(5, value:str) } + if hasBytes { + output.writeData(6, value:bytes) + } unknownFields.writeToCodedOutputStream(output) } override public func serializedSize() -> Int32 { @@ -110,6 +114,9 @@ final public class Perfomance : GeneratedMessage { if hasStr { size += WireFormat.computeStringSize(5, value:str) } + if hasBytes { + size += WireFormat.computeDataSize(6, value:bytes) + } size += unknownFields.serializedSize() memoizedSerializedSize = size return size @@ -160,6 +167,9 @@ final public class Perfomance : GeneratedMessage { if hasStr { output += "\(indent) str: \(str) \n" } + if hasBytes { + output += "\(indent) bytes: \(bytes) \n" + } unknownFields.writeDescriptionTo(&output, indent:indent) } override public var hashValue:Int { @@ -180,6 +190,9 @@ final public class Perfomance : GeneratedMessage { if hasStr { hashCode = (hashCode &* 31) &+ str.hashValue } + for value in bytes { + hashCode = (hashCode &* 31) &+ value.hashValue + } hashCode = (hashCode &* 31) &+ unknownFields.hashValue return hashCode } @@ -302,6 +315,25 @@ final class PerfomanceBuilder : GeneratedMessageBuilder { builderResult.str = "" return self } + var hasBytes:Bool { + get { + return builderResult.hasBytes + } + } + var bytes:Array { + get { + return builderResult.bytes + } + set (value) { + builderResult.hasBytes = true + builderResult.bytes = value + } + } + func clearBytes() -> PerfomanceBuilder{ + builderResult.hasBytes = false + builderResult.bytes = [Byte]() + return self + } override var internalGetResult:GeneratedMessage { get { return builderResult @@ -341,6 +373,9 @@ final class PerfomanceBuilder : GeneratedMessageBuilder { if other.hasStr { str = other.str } + if other.hasBytes { + bytes = other.bytes + } mergeUnknownFields(other.unknownFields) return self } @@ -371,6 +406,9 @@ final class PerfomanceBuilder : GeneratedMessageBuilder { case 42 : str = input.readString() + case 50 : + bytes = input.readData() + default: if (!parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag)) { unknownFields = unknownFieldsBuilder.build() diff --git a/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.proto b/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.proto index cded010..2e0997e 100644 --- a/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.proto +++ b/src/ProtocolBuffers/ProtocolBuffersTests/Perfomance.proto @@ -4,5 +4,6 @@ message Perfomance required int64 ints64 = 2; required double doubles = 3; required float floats = 4; - required string str = 5; + optional string str = 5; + optional bytes bytes = 6; } diff --git a/src/ProtocolBuffers/ProtocolBuffersTests/ProtocolBuffersTests.swift b/src/ProtocolBuffers/ProtocolBuffersTests/ProtocolBuffersTests.swift index db71e66..9690956 100644 --- a/src/ProtocolBuffers/ProtocolBuffersTests/ProtocolBuffersTests.swift +++ b/src/ProtocolBuffers/ProtocolBuffersTests/ProtocolBuffersTests.swift @@ -33,6 +33,7 @@ class ProtocolBuffersTests: XCTestCase { originalBuilder.doubles = Double(12.12) originalBuilder.floats = Float(123.123) originalBuilder.str = "string" + originalBuilder.bytes = [1,2,3,4] let original = originalBuilder.build() self.measureBlock() { for _ in 0...10000 { diff --git a/src/compiler/main.cc b/src/compiler/main.cc index 746f46d..ebc392c 100644 --- a/src/compiler/main.cc +++ b/src/compiler/main.cc @@ -24,7 +24,7 @@ using namespace google::protobuf::compiler::swift; int main(int argc, char **argv) { - - SwiftGenerator generator; - return PluginMain(argc, argv, &generator); + + SwiftGenerator generator; + return PluginMain(argc, argv, &generator); } diff --git a/src/compiler/swift_enum.cc b/src/compiler/swift_enum.cc index b004120..c1434b8 100644 --- a/src/compiler/swift_enum.cc +++ b/src/compiler/swift_enum.cc @@ -27,75 +27,75 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) + + EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor) : descriptor_(descriptor) { - for (int i = 0; i < descriptor_->value_count(); i++) { - const EnumValueDescriptor* value = descriptor_->value(i); - const EnumValueDescriptor* canonical_value = - descriptor_->FindValueByNumber(value->number()); - - if (value == canonical_value) { - canonical_values_.push_back(value); - } else { - Alias alias; - alias.value = value; - alias.canonical_value = canonical_value; - aliases_.push_back(alias); + for (int i = 0; i < descriptor_->value_count(); i++) { + const EnumValueDescriptor* value = descriptor_->value(i); + const EnumValueDescriptor* canonical_value = + descriptor_->FindValueByNumber(value->number()); + + if (value == canonical_value) { + canonical_values_.push_back(value); + } else { + Alias alias; + alias.value = value; + alias.canonical_value = canonical_value; + aliases_.push_back(alias); + } } - } - } - - - EnumGenerator::~EnumGenerator() { - } - - - - - void EnumGenerator::GenerateSource(io::Printer* printer) { - - printer->Print("\n\n//Enum type declaration start \n\n"); - printer->Print( - "enum $classname$:Int32 {\n", - "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - - printer->Indent(); - for (int i = 0; i < canonical_values_.size(); i++) { - printer->Print( - "case $name$ = $value$\n", - "name", EnumValueName(canonical_values_[i]), - "value", SimpleItoa(canonical_values_[i]->number())); - } - printer->Print("\n"); - - printer->Print( - "static func IsValidValue(value:$classname$) ->Bool {\n" - " switch value {\n" - " case .$name$", - "classname", UnderscoresToCapitalizedCamelCase(descriptor_->name()), - "name", EnumValueName(canonical_values_[0])); - - for (int i = 1; i < canonical_values_.size(); i++) { - printer->Print( - ", .$name$", - "name", EnumValueName(canonical_values_[i])); } - printer->Print(":\n"); - - printer->Print( - " return true;\n" - " default:\n" - " return false;\n" - " }\n" - "}\n"); - - printer->Outdent(); - printer->Print( - "}\n" - "\n"); - printer->Print("\n\n//Enum type declaration end \n\n"); - } + + + EnumGenerator::~EnumGenerator() { + } + + + + + void EnumGenerator::GenerateSource(io::Printer* printer) { + + printer->Print("\n\n//Enum type declaration start \n\n"); + printer->Print( + "enum $classname$:Int32 {\n", + "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + + printer->Indent(); + for (int i = 0; i < canonical_values_.size(); i++) { + printer->Print( + "case $name$ = $value$\n", + "name", EnumValueName(canonical_values_[i]), + "value", SimpleItoa(canonical_values_[i]->number())); + } + printer->Print("\n"); + + printer->Print( + "static func IsValidValue(value:$classname$) ->Bool {\n" + " switch value {\n" + " case .$name$", + "classname", UnderscoresToCapitalizedCamelCase(descriptor_->name()), + "name", EnumValueName(canonical_values_[0])); + + for (int i = 1; i < canonical_values_.size(); i++) { + printer->Print( + ", .$name$", + "name", EnumValueName(canonical_values_[i])); + } + printer->Print(":\n"); + + printer->Print( + " return true;\n" + " default:\n" + " return false;\n" + " }\n" + "}\n"); + + printer->Outdent(); + printer->Print( + "}\n" + "\n"); + printer->Print("\n\n//Enum type declaration end \n\n"); + } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_enum.h b/src/compiler/swift_enum.h index c9b1455..e9e15e0 100644 --- a/src/compiler/swift_enum.h +++ b/src/compiler/swift_enum.h @@ -24,39 +24,39 @@ #include namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class EnumGenerator { - public: - explicit EnumGenerator(const EnumDescriptor* descriptor); - ~EnumGenerator(); - - void GenerateSource(io::Printer* printer); - - private: - const EnumDescriptor* descriptor_; - vector canonical_values_; - - struct Alias { - const EnumValueDescriptor* value; - const EnumValueDescriptor* canonical_value; - }; - vector aliases_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); -}; - -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class EnumGenerator { + public: + explicit EnumGenerator(const EnumDescriptor* descriptor); + ~EnumGenerator(); + + void GenerateSource(io::Printer* printer); + + private: + const EnumDescriptor* descriptor_; + vector canonical_values_; + + struct Alias { + const EnumValueDescriptor* value; + const EnumValueDescriptor* canonical_value; + }; + vector aliases_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator); + }; + + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_ENUM_H diff --git a/src/compiler/swift_enum_field.cc b/src/compiler/swift_enum_field.cc index 0e46cd5..d1f08dd 100644 --- a/src/compiler/swift_enum_field.cc +++ b/src/compiler/swift_enum_field.cc @@ -28,340 +28,338 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - namespace { - void SetEnumVariables(const FieldDescriptor* descriptor, - map* variables) { - const EnumValueDescriptor* default_value; - default_value = descriptor->default_value_enum(); - - string type = ClassName(descriptor->enum_type()); - - (*variables)["classname"] = ClassName(descriptor->containing_type()); - (*variables)["name"] = UnderscoresToCamelCase(descriptor); - (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["type"] = type; - (*variables)["default"] = EnumValueName(default_value); - (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); - (*variables)["tag_size"] = SimpleItoa( - internal::WireFormat::TagSize(descriptor->number(), descriptor->type())); - if (isOneOfField(descriptor)) { - const OneofDescriptor* oneof = descriptor->containing_oneof(); - (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); - (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + + namespace { + void SetEnumVariables(const FieldDescriptor* descriptor, + map* variables) { + const EnumValueDescriptor* default_value; + default_value = descriptor->default_value_enum(); + + string type = ClassName(descriptor->enum_type()); + + (*variables)["classname"] = ClassName(descriptor->containing_type()); + (*variables)["name"] = UnderscoresToCamelCase(descriptor); + (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); + (*variables)["number"] = SimpleItoa(descriptor->number()); + (*variables)["type"] = type; + (*variables)["default"] = EnumValueName(default_value); + (*variables)["tag"] = SimpleItoa(internal::WireFormat::MakeTag(descriptor)); + (*variables)["tag_size"] = SimpleItoa( + internal::WireFormat::TagSize(descriptor->number(), descriptor->type())); + if (isOneOfField(descriptor)) { + const OneofDescriptor* oneof = descriptor->containing_oneof(); + (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); + (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + } } - } - } // namespace - - EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor) + } // namespace + + EnumFieldGenerator::EnumFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { - SetEnumVariables(descriptor, &variables_); - } - - - EnumFieldGenerator::~EnumFieldGenerator() { - } - - - void EnumFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { - printer->Print(variables_, - "var $name$:$type$\n"); - } - - void EnumFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - } - - - void EnumFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { - if (isOneOfField(descriptor_)) { - printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" - " get {\n" - " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" - " return false\n" - " }\n" - " return true\n" - " }\n" - " set(newValue) {\n" - " }\n" - "}\n"); - - printer->Print(variables_,"private(set) var $name$:$type$!{\n" - " get {\n" - " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" - " }\n" - " set (newvalue) {\n" - " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" - " }\n" - "}\n"); - } - else - { - printer->Print(variables_, "private(set) var $name$:$type$ = $type$.$default$\n"); - printer->Print(variables_,"private(set) var has$capitalized_name$:Bool = false\n"); - } - } - - - - - void EnumFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { - } - - - void EnumFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - printer->Print(variables_, - " var has$capitalized_name$:Bool{\n" - " get {\n" - " return builderResult.has$capitalized_name$\n" - " }\n" - " }\n" - " var $name$:$type$ {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (value) {\n" - " builderResult.has$capitalized_name$ = true\n" - " builderResult.$name$ = value\n" - " }\n" - " }\n"); - - printer->Print(variables_, - " func clear$capitalized_name$() -> $classname$Builder {\n" - " builderResult.has$capitalized_name$ = false\n" - " builderResult.$name$ = .$default$\n" - " return self\n" - " }\n"); - } - - - - void EnumFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if other.has$capitalized_name$ {\n" - " $name$ = other.$name$\n" - "}\n"); - } - - - void EnumFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - void EnumFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - - "var value = input.readEnum()\n" - "var enumMergResult:$type$ = $type$(rawValue:value)!\n" - "if ($type$.IsValidValue(enumMergResult)) {\n" - " $name$ = enumMergResult\n" - "} else {\n" - " unknownFieldsBuilder.mergeVarintField($number$, value:Int64(value))\n" - "}\n"); - } - - void EnumFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " output.writeEnum($number$, value:$name$.rawValue)\n" - "}\n"); - } - - - void EnumFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if (has$capitalized_name$) {\n" - " size += WireFormat.computeEnumSize($number$, value:$name$.rawValue)\n" - "}\n"); - } - - - void EnumFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if (has$capitalized_name$) {\n" - " output += \"\\(indent) $name$: \\($name$.rawValue)\\n\"\n" - "}\n"); - } - - - void EnumFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); - } - - - void EnumFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " hashCode = (hashCode &* 31) &+ Int($name$.rawValue)\n" - "}\n"); - } - - - string EnumFieldGenerator::GetBoxedType() const { - return ClassName(descriptor_->enum_type()); - } - - - RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor) + SetEnumVariables(descriptor, &variables_); + } + + + EnumFieldGenerator::~EnumFieldGenerator() { + } + + + void EnumFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + printer->Print(variables_, + "var $name$:$type$\n"); + } + + void EnumFieldGenerator::GenerateMembersSource(io::Printer* printer) const { + } + + + void EnumFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + if (isOneOfField(descriptor_)) { + printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" + " get {\n" + " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" + " return false\n" + " }\n" + " return true\n" + " }\n" + " set(newValue) {\n" + " }\n" + "}\n"); + + printer->Print(variables_,"private(set) var $name$:$type$!{\n" + " get {\n" + " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" + " }\n" + " set (newvalue) {\n" + " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" + " }\n" + "}\n"); + } + else + { + printer->Print(variables_, "private(set) var $name$:$type$ = $type$.$default$\n"); + printer->Print(variables_,"private(set) var has$capitalized_name$:Bool = false\n"); + } + } + + + + + void EnumFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { + } + + + void EnumFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + printer->Print(variables_, + " var has$capitalized_name$:Bool{\n" + " get {\n" + " return builderResult.has$capitalized_name$\n" + " }\n" + " }\n" + " var $name$:$type$ {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (value) {\n" + " builderResult.has$capitalized_name$ = true\n" + " builderResult.$name$ = value\n" + " }\n" + " }\n"); + + printer->Print(variables_, + " func clear$capitalized_name$() -> $classname$Builder {\n" + " builderResult.has$capitalized_name$ = false\n" + " builderResult.$name$ = .$default$\n" + " return self\n" + " }\n"); + } + + + + void EnumFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if other.has$capitalized_name$ {\n" + " $name$ = other.$name$\n" + "}\n"); + } + + + void EnumFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + void EnumFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + + "var value = input.readEnum()\n" + "var enumMergResult:$type$ = $type$(rawValue:value)!\n" + "if ($type$.IsValidValue(enumMergResult)) {\n" + " $name$ = enumMergResult\n" + "} else {\n" + " unknownFieldsBuilder.mergeVarintField($number$, value:Int64(value))\n" + "}\n"); + } + + void EnumFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " output.writeEnum($number$, value:$name$.rawValue)\n" + "}\n"); + } + + + void EnumFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if (has$capitalized_name$) {\n" + " size += WireFormat.computeEnumSize($number$, value:$name$.rawValue)\n" + "}\n"); + } + + + void EnumFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if (has$capitalized_name$) {\n" + " output += \"\\(indent) $name$: \\($name$.rawValue)\\n\"\n" + "}\n"); + } + + + void EnumFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); + } + + + void EnumFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " hashCode = (hashCode &* 31) &+ Int($name$.rawValue)\n" + "}\n"); + } + + + string EnumFieldGenerator::GetBoxedType() const { + return ClassName(descriptor_->enum_type()); + } + + + RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { - SetEnumVariables(descriptor, &variables_); - } - - - RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { - } - - - - void RepeatedEnumFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { - printer->Print(variables_,"var $name$:[$type$] = [$type$]()\n"); - } - - void RepeatedEnumFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { -// printer->Print(variables_, "var $name$:$type$\n"); - } - - - - void RepeatedEnumFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { - } - - void RepeatedEnumFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - printer->Print(variables_, - "private var $name$MemoizedSerializedSize:Int32 = 0\n"); - printer->Print(variables_, - "private(set) var $name$:Array<$type$> = Array<$type$>()\n"); - } - - void RepeatedEnumFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - printer->Print(variables_, - "var $name$:Array<$type$> {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (value) {\n" - " builderResult.$name$ += value\n" - " }\n" - "}\n" - "func clear$capitalized_name$() -> $classname$Builder {\n" - " builderResult.$name$.removeAll(keepCapacity: false)\n" - " return self\n" - "}\n"); - } - - void RepeatedEnumFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if !other.$name$.isEmpty {\n" - " builderResult.$name$ += other.$name$\n" - "}\n" - ); - } - - void RepeatedEnumFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - void RepeatedEnumFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - // If packed, set up the while loop - if (descriptor_->options().packed()) { - printer->Print(variables_, - "var length:Int32 = input.readRawVarint32()\n" - "var oldLimit:Int32 = input.pushLimit(length)\n" - "while input.bytesUntilLimit() > 0 {\n"); - + SetEnumVariables(descriptor, &variables_); } - - printer->Print(variables_, - "var value:$type$ = $type$(rawValue:input.readEnum())!\n" - "if $type$.IsValidValue(value) {\n" - " builderResult.$name$ += [value]\n" - "} else {\n" - " unknownFieldsBuilder.mergeVarintField($number$, value:Int64(value.rawValue))\n" - "}\n"); - - if (descriptor_->options().packed()) { - - printer->Print(variables_, - "}\n" - "input.popLimit(oldLimit)\n"); + + + RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { } - } - - void RepeatedEnumFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - - if (descriptor_->options().packed()) { - printer->Print(variables_, - "if !$name$.isEmpty {\n" - " output.writeRawVarint32($tag$)\n" - " output.writeRawVarint32($name$MemoizedSerializedSize)\n" - "}\n" - "for value in $name$ {\n" - " output.writeEnumNoTag(value.rawValue)\n" - "}\n"); - } else { - printer->Print(variables_, - "for value in $name$ {\n" - " output.writeEnum($number$, value:value.rawValue)\n" - "}\n"); + + + + void RepeatedEnumFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + printer->Print(variables_,"var $name$:[$type$] = [$type$]()\n"); } - } - - - void RepeatedEnumFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "var dataSize$name$:Int32 = 0\n"); - - printer->Print(variables_, - "for value in $name$ {\n" - " dataSize$name$ += WireFormat.computeEnumSizeNoTag(value.rawValue)\n" - "}\n"); - - printer->Print(variables_,"size += dataSize$name$\n"); - - if (descriptor_->options().packed()) { - + void RepeatedEnumFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + // printer->Print(variables_, "var $name$:$type$\n"); + } + + + + void RepeatedEnumFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { + } + + void RepeatedEnumFieldGenerator::GenerateMembersSource(io::Printer* printer) const { printer->Print(variables_, - "if !$name$.isEmpty {\n" - " size += $tag_size$\n" - " size += WireFormat.computeRawVarint32Size(dataSize$name$)\n" - "}\n"); - - } else { - printer->Print(variables_, - "size += ($tag_size$ * Int32($name$.count))\n"); + "private var $name$MemoizedSerializedSize:Int32 = 0\n"); + printer->Print(variables_, + "private(set) var $name$:Array<$type$> = Array<$type$>()\n"); } - - if (descriptor_->options().packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize$name$\n"); + + void RepeatedEnumFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + printer->Print(variables_, + "var $name$:Array<$type$> {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (value) {\n" + " builderResult.$name$ += value\n" + " }\n" + "}\n" + "func clear$capitalized_name$() -> $classname$Builder {\n" + " builderResult.$name$.removeAll(keepCapacity: false)\n" + " return self\n" + "}\n"); } - -// printer->Print("}\n"); - } - - - void RepeatedEnumFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "var $name$ElementIndex:Int = 0\n" - "for element in $name$ {\n" - " output += \"\\(indent) $name$[\\($name$ElementIndex)]: \\(element.rawValue)\"\n" - " $name$ElementIndex++\n" - "}\n"); - } - - - void RepeatedEnumFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, "(lhs.$name$ == rhs.$name$)"); - } - - - void RepeatedEnumFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "for element in $name$ {\n" - " hashCode = (hashCode &* 31) &+ Int(element.rawValue)\n" - "}\n"); - } + void RepeatedEnumFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if !other.$name$.isEmpty {\n" + " builderResult.$name$ += other.$name$\n" + "}\n" + ); + } + + void RepeatedEnumFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + void RepeatedEnumFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + // If packed, set up the while loop + if (descriptor_->options().packed()) { + printer->Print(variables_, + "var length:Int32 = input.readRawVarint32()\n" + "var oldLimit:Int32 = input.pushLimit(length)\n" + "while input.bytesUntilLimit() > 0 {\n"); + + } + + printer->Print(variables_, + "var value:$type$ = $type$(rawValue:input.readEnum())!\n" + "if $type$.IsValidValue(value) {\n" + " builderResult.$name$ += [value]\n" + "} else {\n" + " unknownFieldsBuilder.mergeVarintField($number$, value:Int64(value.rawValue))\n" + "}\n"); + + if (descriptor_->options().packed()) { + + printer->Print(variables_, + "}\n" + "input.popLimit(oldLimit)\n"); + } + } + + void RepeatedEnumFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + + if (descriptor_->options().packed()) { + printer->Print(variables_, + "if !$name$.isEmpty {\n" + " output.writeRawVarint32($tag$)\n" + " output.writeRawVarint32($name$MemoizedSerializedSize)\n" + "}\n" + "for value in $name$ {\n" + " output.writeEnumNoTag(value.rawValue)\n" + "}\n"); + } else { + printer->Print(variables_, + "for value in $name$ {\n" + " output.writeEnum($number$, value:value.rawValue)\n" + "}\n"); + } + } + + + void RepeatedEnumFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "var dataSize$name$:Int32 = 0\n"); + + + printer->Print(variables_, + "for value in $name$ {\n" + " dataSize$name$ += WireFormat.computeEnumSizeNoTag(value.rawValue)\n" + "}\n"); + + printer->Print(variables_,"size += dataSize$name$\n"); + + if (descriptor_->options().packed()) { + + printer->Print(variables_, + "if !$name$.isEmpty {\n" + " size += $tag_size$\n" + " size += WireFormat.computeRawVarint32Size(dataSize$name$)\n" + "}\n"); + + } else { + printer->Print(variables_, + "size += ($tag_size$ * Int32($name$.count))\n"); + } + + if (descriptor_->options().packed()) { + printer->Print(variables_, + "$name$MemoizedSerializedSize = dataSize$name$\n"); + } + + } + + + void RepeatedEnumFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "var $name$ElementIndex:Int = 0\n" + "for element in $name$ {\n" + " output += \"\\(indent) $name$[\\($name$ElementIndex)]: \\(element.rawValue)\"\n" + " $name$ElementIndex++\n" + "}\n"); + } + + + void RepeatedEnumFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, "(lhs.$name$ == rhs.$name$)"); + } + + + void RepeatedEnumFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "for element in $name$ {\n" + " hashCode = (hashCode &* 31) &+ Int(element.rawValue)\n" + "}\n"); + } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_enum_field.h b/src/compiler/swift_enum_field.h index 5e7b5db..da16377 100644 --- a/src/compiler/swift_enum_field.h +++ b/src/compiler/swift_enum_field.h @@ -24,69 +24,69 @@ #include "swift_field.h" namespace google { -namespace protobuf { -namespace compiler { -namespace swift { - -class EnumFieldGenerator : public FieldGenerator { - public: - explicit EnumFieldGenerator(const FieldDescriptor* descriptor); - ~EnumFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); -}; - -class RepeatedEnumFieldGenerator : public FieldGenerator { - public: - explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor); - ~RepeatedEnumFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); -}; - -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace compiler { + namespace swift { + + class EnumFieldGenerator : public FieldGenerator { + public: + explicit EnumFieldGenerator(const FieldDescriptor* descriptor); + ~EnumFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + string GetBoxedType() const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); + }; + + class RepeatedEnumFieldGenerator : public FieldGenerator { + public: + explicit RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor); + ~RepeatedEnumFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + string GetBoxedType() const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); + }; + + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_ENUM_FIELD_H diff --git a/src/compiler/swift_extension.cc b/src/compiler/swift_extension.cc index c4d3c0c..cdbfbe9 100644 --- a/src/compiler/swift_extension.cc +++ b/src/compiler/swift_extension.cc @@ -25,65 +25,65 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - ExtensionGenerator::ExtensionGenerator(string classname, const FieldDescriptor* descriptor) + + ExtensionGenerator::ExtensionGenerator(string classname, const FieldDescriptor* descriptor) : classname_(classname), descriptor_(descriptor) { - } - - - ExtensionGenerator::~ExtensionGenerator() { - } - - -void ExtensionGenerator::GenerateFieldsGetterSource(io::Printer* printer, string rootclassname) { - map vars; - vars["name"] = UnderscoresToCamelCase(descriptor_); - vars["containing_type"] = classname_; - vars["root_name"] = rootclassname; + } - SwiftType java_type = GetSwiftType(descriptor_); - string singular_type; - switch (java_type) { - case SWIFTTYPE_MESSAGE: - vars["type"] = ClassName(descriptor_->message_type()); - break; - default: - vars["type"] = BoxedPrimitiveTypeName(java_type); - break; + + ExtensionGenerator::~ExtensionGenerator() { } - vars["extended_type"] = ClassName(descriptor_->containing_type()); - printer->Print(vars,"var $containing_type$$name$:ConcreateExtensionField {\n" - " get {\n" - " return $root_name$.sharedInstance.$containing_type$$name$Static\n" - " }\n" - "}\n"); -} - - void ExtensionGenerator::GenerateFieldsSource(io::Printer* printer) { - map vars; - vars["name"] = UnderscoresToCamelCase(descriptor_); - vars["containing_type"] = classname_; - - SwiftType java_type = GetSwiftType(descriptor_); - string singular_type; - switch (java_type) { - case SWIFTTYPE_MESSAGE: - vars["type"] = ClassName(descriptor_->message_type()); - break; - default: - vars["type"] = BoxedPrimitiveTypeName(java_type); - break; - } - - vars["extended_type"] = ClassName(descriptor_->containing_type()); - - printer->Print(vars, - "var $containing_type$$name$Static:ConcreateExtensionField\n"); - } - + void ExtensionGenerator::GenerateFieldsGetterSource(io::Printer* printer, string rootclassname) { + map vars; + vars["name"] = UnderscoresToCamelCase(descriptor_); + vars["containing_type"] = classname_; + vars["root_name"] = rootclassname; + + SwiftType java_type = GetSwiftType(descriptor_); + string singular_type; + switch (java_type) { + case SWIFTTYPE_MESSAGE: + vars["type"] = ClassName(descriptor_->message_type()); + break; + default: + vars["type"] = BoxedPrimitiveTypeName(java_type); + break; + } + + vars["extended_type"] = ClassName(descriptor_->containing_type()); + + printer->Print(vars,"var $containing_type$$name$:ConcreateExtensionField {\n" + " get {\n" + " return $root_name$.sharedInstance.$containing_type$$name$Static\n" + " }\n" + "}\n"); + } + + void ExtensionGenerator::GenerateFieldsSource(io::Printer* printer) { + map vars; + vars["name"] = UnderscoresToCamelCase(descriptor_); + vars["containing_type"] = classname_; + + SwiftType java_type = GetSwiftType(descriptor_); + string singular_type; + switch (java_type) { + case SWIFTTYPE_MESSAGE: + vars["type"] = ClassName(descriptor_->message_type()); + break; + default: + vars["type"] = BoxedPrimitiveTypeName(java_type); + break; + } + + vars["extended_type"] = ClassName(descriptor_->containing_type()); + + printer->Print(vars, + "var $containing_type$$name$Static:ConcreateExtensionField\n"); + } + void ExtensionGenerator::GenerateMembersSourceExtensions(io::Printer* printer, string fileClass) { map vars; vars["name"] = UnderscoresToCamelCase(descriptor_); @@ -95,102 +95,103 @@ void ExtensionGenerator::GenerateFieldsGetterSource(io::Printer* printer, string " return $rootclass_type$.sharedInstance.$containing_type$$name$Static\n" "}\n"); } - - void ExtensionGenerator::GenerateMembersSource(io::Printer* printer) { - map vars; - vars["name"] = UnderscoresToCamelCase(descriptor_); - vars["containing_type"] = classname_; - - printer->Print(vars, - "class func $name$() -> ConcreateExtensionField {\n" - " return $containing_type$$name$\n" - "}\n"); - } - - void ExtensionGenerator::GenerateInitializationSource(io::Printer* printer) { - map vars; - vars["name"] = UnderscoresToCamelCase(descriptor_); - vars["containing_type"] = classname_; - vars["extended_type"] = ClassName(descriptor_->containing_type()); - vars["number"] = SimpleItoa(descriptor_->number()); - - const bool isPacked = descriptor_->options().packed(); - vars["is_repeated"] = descriptor_->is_repeated() ? "true" : "false"; - vars["is_packed"] = isPacked ? "true" : "false"; - vars["is_wire_format"] = descriptor_->containing_type()->options().message_set_wire_format() ? "true" : "false"; - - SwiftType java_type = GetSwiftType(descriptor_); - string singular_type; - switch (java_type) { - case SWIFTTYPE_MESSAGE: - vars["type"] = ClassName(descriptor_->message_type()); - break; - default: - vars["type"] = BoxedPrimitiveTypeName(java_type); - break; - } - - switch (descriptor_->type()) { - case FieldDescriptor::TYPE_INT32: - vars["extension_type"] = "ExtensionType.ExtensionTypeInt32"; - break; - case FieldDescriptor::TYPE_UINT32: - vars["extension_type"] = "ExtensionType.ExtensionTypeUInt32"; - break; - case FieldDescriptor::TYPE_SINT32: - vars["extension_type"] = "ExtensionType.ExtensionTypeSInt32"; - break; - case FieldDescriptor::TYPE_FIXED32: - vars["extension_type"] = "ExtensionType.ExtensionTypeFixed32"; - break; - case FieldDescriptor::TYPE_SFIXED32: - vars["extension_type"] = "ExtensionType.ExtensionTypeSFixed32"; - break; - case FieldDescriptor::TYPE_INT64: - vars["extension_type"] = "ExtensionType.ExtensionTypeInt64"; - break; - case FieldDescriptor::TYPE_UINT64: - vars["extension_type"] = "ExtensionType.ExtensionTypeUInt64"; - break; - case FieldDescriptor::TYPE_SINT64: - vars["extension_type"] = "ExtensionType.ExtensionTypeSInt64"; - break; - case FieldDescriptor::TYPE_FIXED64: - vars["extension_type"] = "ExtensionType.ExtensionTypeFixed64"; - break; - case FieldDescriptor::TYPE_SFIXED64: - vars["extension_type"] = "ExtensionType.ExtensionTypeSFixed64"; - break; - case FieldDescriptor::TYPE_FLOAT: - vars["extension_type"] = "ExtensionType.ExtensionTypeFloat"; - break; - case FieldDescriptor::TYPE_DOUBLE: - vars["extension_type"] = "ExtensionType.ExtensionTypeDouble"; - break; - case FieldDescriptor::TYPE_BOOL: - vars["extension_type"] = "ExtensionType.ExtensionTypeBool"; - break; - case FieldDescriptor::TYPE_STRING: - vars["extension_type"] = "ExtensionType.ExtensionTypeString"; - break; - case FieldDescriptor::TYPE_BYTES: - vars["extension_type"] = "ExtensionType.ExtensionTypeBytes"; - break; - case FieldDescriptor::TYPE_MESSAGE: - vars["extension_type"] = "ExtensionType.ExtensionTypeMessage"; - break; - case FieldDescriptor::TYPE_ENUM: - vars["extension_type"] = "ExtensionType.ExtensionTypeEnum"; - break; - case FieldDescriptor::TYPE_GROUP: - vars["extension_type"] = "ExtensionType.ExtensionTypeGroup"; - break; + + void ExtensionGenerator::GenerateMembersSource(io::Printer* printer) { + map vars; + vars["name"] = UnderscoresToCamelCase(descriptor_); + vars["containing_type"] = classname_; + + printer->Print(vars, + "class func $name$() -> ConcreateExtensionField {\n" + " return $containing_type$$name$\n" + "}\n"); } - - if(descriptor_->is_repeated()) + + void ExtensionGenerator::GenerateInitializationSource(io::Printer* printer) { + map vars; + vars["name"] = UnderscoresToCamelCase(descriptor_); + vars["containing_type"] = classname_; + vars["extended_type"] = ClassName(descriptor_->containing_type()); + vars["number"] = SimpleItoa(descriptor_->number()); + + const bool isPacked = descriptor_->options().packed(); + vars["is_repeated"] = descriptor_->is_repeated() ? "true" : "false"; + vars["is_packed"] = isPacked ? "true" : "false"; + vars["is_wire_format"] = descriptor_->containing_type()->options().message_set_wire_format() ? "true" : "false"; + + SwiftType java_type = GetSwiftType(descriptor_); + string singular_type; + switch (java_type) { + case SWIFTTYPE_MESSAGE: + vars["type"] = ClassName(descriptor_->message_type()); + break; + default: + vars["type"] = BoxedPrimitiveTypeName(java_type); + break; + } + + switch (descriptor_->type()) { + case FieldDescriptor::TYPE_INT32: + vars["extension_type"] = "ExtensionType.ExtensionTypeInt32"; + break; + case FieldDescriptor::TYPE_UINT32: + vars["extension_type"] = "ExtensionType.ExtensionTypeUInt32"; + break; + case FieldDescriptor::TYPE_SINT32: + vars["extension_type"] = "ExtensionType.ExtensionTypeSInt32"; + break; + case FieldDescriptor::TYPE_FIXED32: + vars["extension_type"] = "ExtensionType.ExtensionTypeFixed32"; + break; + case FieldDescriptor::TYPE_SFIXED32: + vars["extension_type"] = "ExtensionType.ExtensionTypeSFixed32"; + break; + case FieldDescriptor::TYPE_INT64: + vars["extension_type"] = "ExtensionType.ExtensionTypeInt64"; + break; + case FieldDescriptor::TYPE_UINT64: + vars["extension_type"] = "ExtensionType.ExtensionTypeUInt64"; + break; + case FieldDescriptor::TYPE_SINT64: + vars["extension_type"] = "ExtensionType.ExtensionTypeSInt64"; + break; + case FieldDescriptor::TYPE_FIXED64: + vars["extension_type"] = "ExtensionType.ExtensionTypeFixed64"; + break; + case FieldDescriptor::TYPE_SFIXED64: + vars["extension_type"] = "ExtensionType.ExtensionTypeSFixed64"; + break; + case FieldDescriptor::TYPE_FLOAT: + vars["extension_type"] = "ExtensionType.ExtensionTypeFloat"; + break; + case FieldDescriptor::TYPE_DOUBLE: + vars["extension_type"] = "ExtensionType.ExtensionTypeDouble"; + break; + case FieldDescriptor::TYPE_BOOL: + vars["extension_type"] = "ExtensionType.ExtensionTypeBool"; + break; + case FieldDescriptor::TYPE_STRING: + vars["extension_type"] = "ExtensionType.ExtensionTypeString"; + break; + case FieldDescriptor::TYPE_BYTES: + vars["extension_type"] = "ExtensionType.ExtensionTypeBytes"; + break; + case FieldDescriptor::TYPE_MESSAGE: + vars["extension_type"] = "ExtensionType.ExtensionTypeMessage"; + break; + case FieldDescriptor::TYPE_ENUM: + vars["extension_type"] = "ExtensionType.ExtensionTypeEnum"; + break; + case FieldDescriptor::TYPE_GROUP: + vars["extension_type"] = "ExtensionType.ExtensionTypeGroup"; + break; + } + + if(descriptor_->is_repeated()) { vars["default"] = string("Array<") + vars["type"] + string(">()"); - } + } + else if (descriptor_->type() == FieldDescriptor::TYPE_ENUM) { vars["default"] = ClassName(descriptor_->enum_type()) + "." + EnumValueName(descriptor_->default_value_enum()) + ".rawValue"; @@ -199,18 +200,16 @@ void ExtensionGenerator::GenerateFieldsGetterSource(io::Printer* printer, string { vars["default"] = DefaultValue(descriptor_); } - - - - printer->Print(vars,"$containing_type$$name$Static = ConcreateExtensionField(type:$extension_type$, extendedClass:$extended_type$.self, fieldNumber: $number$, defaultValue:$default$, messageOrGroupClass:$type$.self, isRepeated:$is_repeated$, isPacked:$is_packed$, isMessageSetWireFormat:$is_wire_format$)\n"); - } - - void ExtensionGenerator::GenerateRegistrationSource(io::Printer* printer) { - printer->Print( - "registry.addExtension($scope$$name$Static)\n", - "scope", classname_, - "name", UnderscoresToCamelCase(descriptor_)); - } + + printer->Print(vars,"$containing_type$$name$Static = ConcreateExtensionField(type:$extension_type$, extendedClass:$extended_type$.self, fieldNumber: $number$, defaultValue:$default$, messageOrGroupClass:$type$.self, isRepeated:$is_repeated$, isPacked:$is_packed$, isMessageSetWireFormat:$is_wire_format$)\n"); + } + + void ExtensionGenerator::GenerateRegistrationSource(io::Printer* printer) { + printer->Print( + "registry.addExtension($scope$$name$Static)\n", + "scope", classname_, + "name", UnderscoresToCamelCase(descriptor_)); + } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_extension.h b/src/compiler/swift_extension.h index 211f678..aeadec5 100644 --- a/src/compiler/swift_extension.h +++ b/src/compiler/swift_extension.h @@ -21,37 +21,37 @@ #include namespace google { -namespace protobuf { - class FieldDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class ExtensionGenerator { - public: - explicit ExtensionGenerator(string classname, const FieldDescriptor* descriptor); - ~ExtensionGenerator(); - - void GenerateMembersSource(io::Printer* printer); - void GenerateMembersSourceExtensions(io::Printer* printer, string fileClass); - void GenerateFieldsSource(io::Printer* printer); - void GenerateFieldsGetterSource(io::Printer* printer, string rootclassname); - void GenerateInitializationSource(io::Printer* printer); - void GenerateRegistrationSource(io::Printer* printer); - - private: - string classname_; - const FieldDescriptor* descriptor_; - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + class FieldDescriptor; // descriptor.h + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class ExtensionGenerator { + public: + explicit ExtensionGenerator(string classname, const FieldDescriptor* descriptor); + ~ExtensionGenerator(); + + void GenerateMembersSource(io::Printer* printer); + void GenerateMembersSourceExtensions(io::Printer* printer, string fileClass); + void GenerateFieldsSource(io::Printer* printer); + void GenerateFieldsGetterSource(io::Printer* printer, string rootclassname); + void GenerateInitializationSource(io::Printer* printer); + void GenerateRegistrationSource(io::Printer* printer); + + private: + string classname_; + const FieldDescriptor* descriptor_; + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_MESSAGE_H diff --git a/src/compiler/swift_field.cc b/src/compiler/swift_field.cc index 316b87f..e1a0565 100644 --- a/src/compiler/swift_field.cc +++ b/src/compiler/swift_field.cc @@ -23,68 +23,67 @@ #include "swift_helpers.h" #include "swift_primitive_field.h" #include "swift_enum_field.h" -//#include "swift_oneof.h" #include "swift_message_field.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - FieldGenerator::~FieldGenerator() { - } - - - FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor) + + FieldGenerator::~FieldGenerator() { + } + + + FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor) : descriptor_(descriptor), field_generators_(new scoped_ptr[descriptor->field_count()]), extension_generators_(new scoped_ptr[descriptor->extension_count()]){ -// oneof_generators_(new scoped_ptr[descriptor->oneof_count()]) { - - for (int i = 0; i < descriptor->field_count(); i++) { - field_generators_[i].reset(MakeGenerator(descriptor->field(i))); - } - for (int i = 0; i < descriptor->extension_count(); i++) { - extension_generators_[i].reset(MakeGenerator(descriptor->extension(i))); - } + // oneof_generators_(new scoped_ptr[descriptor->oneof_count()]) { + + for (int i = 0; i < descriptor->field_count(); i++) { + field_generators_[i].reset(MakeGenerator(descriptor->field(i))); + } + for (int i = 0; i < descriptor->extension_count(); i++) { + extension_generators_[i].reset(MakeGenerator(descriptor->extension(i))); + } } - - - FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field) { - if (field->is_repeated()) { - switch (GetSwiftType(field)) { - case SWIFTTYPE_MESSAGE: - return new RepeatedMessageFieldGenerator(field); - case SWIFTTYPE_ENUM: - return new RepeatedEnumFieldGenerator(field); - default: - return new RepeatedPrimitiveFieldGenerator(field); - } - } else { - switch (GetSwiftType(field)) { - case SWIFTTYPE_MESSAGE: - return new MessageFieldGenerator(field); - case SWIFTTYPE_ENUM: - return new EnumFieldGenerator(field); - default: - return new PrimitiveFieldGenerator(field); - } + + + FieldGenerator* FieldGeneratorMap::MakeGenerator(const FieldDescriptor* field) { + if (field->is_repeated()) { + switch (GetSwiftType(field)) { + case SWIFTTYPE_MESSAGE: + return new RepeatedMessageFieldGenerator(field); + case SWIFTTYPE_ENUM: + return new RepeatedEnumFieldGenerator(field); + default: + return new RepeatedPrimitiveFieldGenerator(field); + } + } else { + switch (GetSwiftType(field)) { + case SWIFTTYPE_MESSAGE: + return new MessageFieldGenerator(field); + case SWIFTTYPE_ENUM: + return new EnumFieldGenerator(field); + default: + return new PrimitiveFieldGenerator(field); + } + } + } + + + FieldGeneratorMap::~FieldGeneratorMap() { + } + + + const FieldGenerator& FieldGeneratorMap::get( + const FieldDescriptor* field) const { + GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); + return *field_generators_[field->index()]; + } + + + const FieldGenerator& FieldGeneratorMap::get_extension(int index) const { + return *extension_generators_[index]; } - } - - - FieldGeneratorMap::~FieldGeneratorMap() { - } - - - const FieldGenerator& FieldGeneratorMap::get( - const FieldDescriptor* field) const { - GOOGLE_CHECK_EQ(field->containing_type(), descriptor_); - return *field_generators_[field->index()]; - } - - - const FieldGenerator& FieldGeneratorMap::get_extension(int index) const { - return *extension_generators_[index]; - } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_field.h b/src/compiler/swift_field.h index d6f633f..b68e327 100644 --- a/src/compiler/swift_field.h +++ b/src/compiler/swift_field.h @@ -23,61 +23,61 @@ #include namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class FieldGenerator { - public: - FieldGenerator() {} - virtual ~FieldGenerator(); - - virtual void GenerateExtensionSource(io::Printer* printer) const = 0; - virtual void GenerateSynthesizeSource(io::Printer* printer) const = 0; - virtual void GenerateInitializationSource(io::Printer* printer) const = 0; - virtual void GenerateMembersSource(io::Printer* printer) const = 0; - virtual void GenerateBuilderMembersSource(io::Printer* printer) const = 0; - virtual void GenerateMergingCodeSource(io::Printer* printer) const = 0; - virtual void GenerateBuildingCodeSource(io::Printer* printer) const = 0; - virtual void GenerateParsingCodeSource(io::Printer* printer) const = 0; - virtual void GenerateSerializationCodeSource(io::Printer* printer) const = 0; - virtual void GenerateSerializedSizeCodeSource(io::Printer* printer) const = 0; - virtual void GenerateDescriptionCodeSource(io::Printer* printer) const = 0; - virtual void GenerateIsEqualCodeSource(io::Printer* printer) const = 0; - virtual void GenerateHashCodeSource(io::Printer* printer) const = 0; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); -}; - -// Convenience class which constructs FieldGenerators for a Descriptor. -class FieldGeneratorMap { - public: - explicit FieldGeneratorMap(const Descriptor* descriptor); - ~FieldGeneratorMap(); - - const FieldGenerator& get(const FieldDescriptor* field) const; - const FieldGenerator& get_extension(int index) const; - - private: - const Descriptor* descriptor_; - scoped_array > field_generators_; - scoped_array > extension_generators_; - scoped_array > oneof_generators_; - - static FieldGenerator* MakeGenerator(const FieldDescriptor* field); - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class FieldGenerator { + public: + FieldGenerator() {} + virtual ~FieldGenerator(); + + virtual void GenerateExtensionSource(io::Printer* printer) const = 0; + virtual void GenerateSynthesizeSource(io::Printer* printer) const = 0; + virtual void GenerateInitializationSource(io::Printer* printer) const = 0; + virtual void GenerateMembersSource(io::Printer* printer) const = 0; + virtual void GenerateBuilderMembersSource(io::Printer* printer) const = 0; + virtual void GenerateMergingCodeSource(io::Printer* printer) const = 0; + virtual void GenerateBuildingCodeSource(io::Printer* printer) const = 0; + virtual void GenerateParsingCodeSource(io::Printer* printer) const = 0; + virtual void GenerateSerializationCodeSource(io::Printer* printer) const = 0; + virtual void GenerateSerializedSizeCodeSource(io::Printer* printer) const = 0; + virtual void GenerateDescriptionCodeSource(io::Printer* printer) const = 0; + virtual void GenerateIsEqualCodeSource(io::Printer* printer) const = 0; + virtual void GenerateHashCodeSource(io::Printer* printer) const = 0; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); + }; + + // Convenience class which constructs FieldGenerators for a Descriptor. + class FieldGeneratorMap { + public: + explicit FieldGeneratorMap(const Descriptor* descriptor); + ~FieldGeneratorMap(); + + const FieldGenerator& get(const FieldDescriptor* field) const; + const FieldGenerator& get_extension(int index) const; + + private: + const Descriptor* descriptor_; + scoped_array > field_generators_; + scoped_array > extension_generators_; + scoped_array > oneof_generators_; + + static FieldGenerator* MakeGenerator(const FieldDescriptor* field); + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_FIELD_H diff --git a/src/compiler/swift_file.cc b/src/compiler/swift_file.cc index ab34015..a07b1a1 100644 --- a/src/compiler/swift_file.cc +++ b/src/compiler/swift_file.cc @@ -32,165 +32,165 @@ #include "swift_message.h" namespace google { namespace protobuf { namespace compiler {namespace swift { - - FileGenerator::FileGenerator(const FileDescriptor* file) + + FileGenerator::FileGenerator(const FileDescriptor* file) : file_(file), classname_(FileClassName(file)) { - } - - - FileGenerator::~FileGenerator() { - } - - void DetermineDependenciesWorker(set* dependencies, set* seen_files, const FileDescriptor* file) { - if (seen_files->find(file->name()) != seen_files->end()) { - // don't infinitely recurse - return; } - - seen_files->insert(file->name()); - - for (int i = 0; i < file->dependency_count(); i++) { - DetermineDependenciesWorker(dependencies, seen_files, file->dependency(i)); - } - for (int i = 0; i < file->message_type_count(); i++) { - MessageGenerator(file->message_type(i)).DetermineDependencies(dependencies); - } - } - - - void FileGenerator::DetermineDependencies(set* dependencies) { - set seen_files; - DetermineDependenciesWorker(dependencies, &seen_files, file_); - } - - - void FileGenerator::GenerateSource(io::Printer* printer) { - FileGenerator file_generator(file_); - printer->Print( - "// Generated by the protocol buffer compiler. DO NOT EDIT!\n\n" - "import Foundation\n" - "import ProtocolBuffers\n\n"); - - //fields - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(classname_, file_->extension(i)).GenerateFieldsGetterSource(printer, classname_); - } - - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i)).GenerateGlobalStaticVariablesSource(printer, classname_); - } - - printer->Print( - "struct $classname$ {\n", - "classname", classname_); - - printer->Indent(); - printer->Print( - "static var sharedInstance : $classname$ {\n" - " struct Static {\n" - " static let instance : $classname$ = $classname$()\n" - " }\n" - " return Static.instance\n" - "}\n","classname", classname_); - - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(classname_, file_->extension(i)).GenerateFieldsSource(printer); - } - - - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i)).GenerateStaticVariablesSource(printer); - } - - //TODO - printer->Print("var extensionRegistry:ExtensionRegistry\n"); - printer->Print( - "\n" - "init() {\n"); - - printer->Indent(); - - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(classname_, file_->extension(i)).GenerateInitializationSource(printer); - } - - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i)).GenerateStaticVariablesInitialization(printer); - } - - printer->Print( - "extensionRegistry = ExtensionRegistry()\n" - "registerAllExtensions(extensionRegistry)\n"); - - for (int i = 0; i < file_->dependency_count(); i++) { - printer->Print( - "$dependency$.sharedInstance.registerAllExtensions(extensionRegistry)\n", - "dependency", FileClassName(file_->dependency(i))); + + FileGenerator::~FileGenerator() { } - printer->Outdent(); - printer->Print( - "" - "}\n"); + void DetermineDependenciesWorker(set* dependencies, set* seen_files, const FileDescriptor* file) { + if (seen_files->find(file->name()) != seen_files->end()) { + // don't infinitely recurse + return; + } + + seen_files->insert(file->name()); + + for (int i = 0; i < file->dependency_count(); i++) { + DetermineDependenciesWorker(dependencies, seen_files, file->dependency(i)); + } + for (int i = 0; i < file->message_type_count(); i++) { + MessageGenerator(file->message_type(i)).DetermineDependencies(dependencies); + } + } - - printer->Print( - "func registerAllExtensions(registry:ExtensionRegistry) {\n"); - printer->Indent(); - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(classname_, file_->extension(i)) - .GenerateRegistrationSource(printer); - } - - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i)) - .GenerateExtensionRegistrationSource(printer); - } - printer->Outdent(); - printer->Print("}\n"); - - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator(classname_, file_->extension(i)).GenerateMembersSourceExtensions(printer,classname_); + void FileGenerator::DetermineDependencies(set* dependencies) { + set seen_files; + DetermineDependenciesWorker(dependencies, &seen_files, file_); } - - printer->Outdent(); - printer->Print("}\n\n"); - - for (int i = 0; i < file_->enum_type_count(); i++) { - EnumGenerator(file_->enum_type(i)).GenerateSource(printer); - } - for (int i = 0; i < file_->message_type_count(); i++) { - - for (int j = 0; j < file_->message_type(i)->nested_type_count(); j++) { - MessageGenerator(file_->message_type(i)->nested_type(j)).GenerateMessageIsEqualSource(printer); + void FileGenerator::GenerateSource(io::Printer* printer) { + FileGenerator file_generator(file_); + printer->Print( + "// Generated by the protocol buffer compiler. DO NOT EDIT!\n\n" + "import Foundation\n" + "import ProtocolBuffers\n\n"); + + //fields + for (int i = 0; i < file_->extension_count(); i++) { + ExtensionGenerator(classname_, file_->extension(i)).GenerateFieldsGetterSource(printer, classname_); } - MessageGenerator(file_->message_type(i)).GenerateMessageIsEqualSource(printer); - } - - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator(file_->message_type(i)).GenerateSource(printer); - } - - //Extensions NSData - printer->Print("//Class extensions: NSData\n\n\n"); - - for (int i = 0; i < file_->message_type_count(); i++) { - - for (int j = 0; j < file_->message_type(i)->nested_type_count(); j++) { - MessageGenerator(file_->message_type(i)->nested_type(j)).GenerateParseFromExtensionMethodsSource(printer); - } - MessageGenerator(file_->message_type(i)).GenerateParseFromExtensionMethodsSource(printer); + + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator(file_->message_type(i)).GenerateGlobalStaticVariablesSource(printer, classname_); + } + + printer->Print( + "struct $classname$ {\n", + "classname", classname_); + + printer->Indent(); + printer->Print( + "static var sharedInstance : $classname$ {\n" + " struct Static {\n" + " static let instance : $classname$ = $classname$()\n" + " }\n" + " return Static.instance\n" + "}\n","classname", classname_); + + for (int i = 0; i < file_->extension_count(); i++) { + ExtensionGenerator(classname_, file_->extension(i)).GenerateFieldsSource(printer); + } + + + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator(file_->message_type(i)).GenerateStaticVariablesSource(printer); + } + + //TODO + printer->Print("var extensionRegistry:ExtensionRegistry\n"); + printer->Print( + "\n" + "init() {\n"); + + printer->Indent(); + + + for (int i = 0; i < file_->extension_count(); i++) { + ExtensionGenerator(classname_, file_->extension(i)).GenerateInitializationSource(printer); + } + + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator(file_->message_type(i)).GenerateStaticVariablesInitialization(printer); + } + + printer->Print( + "extensionRegistry = ExtensionRegistry()\n" + "registerAllExtensions(extensionRegistry)\n"); + + for (int i = 0; i < file_->dependency_count(); i++) { + printer->Print( + "$dependency$.sharedInstance.registerAllExtensions(extensionRegistry)\n", + "dependency", FileClassName(file_->dependency(i))); + } + + printer->Outdent(); + printer->Print( + "" + "}\n"); + + + printer->Print( + "func registerAllExtensions(registry:ExtensionRegistry) {\n"); + + printer->Indent(); + for (int i = 0; i < file_->extension_count(); i++) { + ExtensionGenerator(classname_, file_->extension(i)) + .GenerateRegistrationSource(printer); + } + + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator(file_->message_type(i)) + .GenerateExtensionRegistrationSource(printer); + } + printer->Outdent(); + printer->Print("}\n"); + + for (int i = 0; i < file_->extension_count(); i++) { + ExtensionGenerator(classname_, file_->extension(i)).GenerateMembersSourceExtensions(printer,classname_); + } + + printer->Outdent(); + printer->Print("}\n\n"); + + + for (int i = 0; i < file_->enum_type_count(); i++) { + EnumGenerator(file_->enum_type(i)).GenerateSource(printer); + } + + for (int i = 0; i < file_->message_type_count(); i++) { + + for (int j = 0; j < file_->message_type(i)->nested_type_count(); j++) { + MessageGenerator(file_->message_type(i)->nested_type(j)).GenerateMessageIsEqualSource(printer); + } + MessageGenerator(file_->message_type(i)).GenerateMessageIsEqualSource(printer); + } + + for (int i = 0; i < file_->message_type_count(); i++) { + MessageGenerator(file_->message_type(i)).GenerateSource(printer); + } + + //Extensions NSData + printer->Print("//Class extensions: NSData\n\n\n"); + + for (int i = 0; i < file_->message_type_count(); i++) { + + for (int j = 0; j < file_->message_type(i)->nested_type_count(); j++) { + MessageGenerator(file_->message_type(i)->nested_type(j)).GenerateParseFromExtensionMethodsSource(printer); + } + MessageGenerator(file_->message_type(i)).GenerateParseFromExtensionMethodsSource(printer); + } + + printer->Print( + "\n" + "// @@protoc_insertion_point(global_scope)\n"); } - - printer->Print( - "\n" - "// @@protoc_insertion_point(global_scope)\n"); - } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_file.h b/src/compiler/swift_file.h index 74f1b7a..7ff70ae 100644 --- a/src/compiler/swift_file.h +++ b/src/compiler/swift_file.h @@ -24,36 +24,36 @@ #include namespace google { -namespace protobuf { - class FileDescriptor; // descriptor.h - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class FileGenerator { - public: - explicit FileGenerator(const FileDescriptor* file); - ~FileGenerator(); - - void GenerateSource(io::Printer* printer); - void DetermineDependencies(set* dependencies); - - const string& classname() { return classname_; } - - private: - const FileDescriptor* file_; - string classname_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + class FileDescriptor; // descriptor.h + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class FileGenerator { + public: + explicit FileGenerator(const FileDescriptor* file); + ~FileGenerator(); + + void GenerateSource(io::Printer* printer); + void DetermineDependencies(set* dependencies); + + const string& classname() { return classname_; } + + private: + const FileDescriptor* file_; + string classname_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_FILE_H__ diff --git a/src/compiler/swift_generator.cc b/src/compiler/swift_generator.cc index f498fca..b42d465 100644 --- a/src/compiler/swift_generator.cc +++ b/src/compiler/swift_generator.cc @@ -26,45 +26,45 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - SwiftGenerator::SwiftGenerator() { - } - - - SwiftGenerator::~SwiftGenerator() { - } - - - bool SwiftGenerator::Generate(const FileDescriptor* file, - const string& parameter, - OutputDirectory* output_directory, - string* error) const { - vector > options; - ParseGeneratorParameter(parameter, &options); - - string output_list_file; - - for (int i = 0; i < options.size(); i++) { - if (options[i].first == "output_list_file") { - output_list_file = options[i].second; - } else { - *error = "Unknown generator option: " + options[i].first; - return false; + SwiftGenerator::SwiftGenerator() { + } + + + SwiftGenerator::~SwiftGenerator() { + } + + + bool SwiftGenerator::Generate(const FileDescriptor* file, + const string& parameter, + OutputDirectory* output_directory, + string* error) const { + vector > options; + ParseGeneratorParameter(parameter, &options); + + string output_list_file; + + for (int i = 0; i < options.size(); i++) { + if (options[i].first == "output_list_file") { + output_list_file = options[i].second; + } else { + *error = "Unknown generator option: " + options[i].first; + return false; + } } - } - - FileGenerator file_generator(file); - - string filepath = FilePath(file); - { - scoped_ptr output( - output_directory->Open(filepath + ".pb.swift")); - io::Printer printer(output.get(), '$'); - file_generator.GenerateSource(&printer); - } - - return true; - } - + + FileGenerator file_generator(file); + + string filepath = FilePath(file); + { + scoped_ptr output( + output_directory->Open(filepath + ".pb.swift")); + io::Printer printer(output.get(), '$'); + file_generator.GenerateSource(&printer); + } + + return true; + } + } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_generator.h b/src/compiler/swift_generator.h index 2a3a913..97ab0f0 100644 --- a/src/compiler/swift_generator.h +++ b/src/compiler/swift_generator.h @@ -22,26 +22,26 @@ #include namespace google { -namespace protobuf { -namespace compiler { -namespace swift { - -class SwiftGenerator : public CodeGenerator { - public: - SwiftGenerator(); - ~SwiftGenerator(); - - bool Generate(const FileDescriptor* file, - const string& parameter, - OutputDirectory* output_directory, - string* error) const; - - private: - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SwiftGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace compiler { + namespace swift { + + class SwiftGenerator : public CodeGenerator { + public: + SwiftGenerator(); + ~SwiftGenerator(); + + bool Generate(const FileDescriptor* file, + const string& parameter, + OutputDirectory* output_directory, + string* error) const; + + private: + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SwiftGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_GENERATOR_H diff --git a/src/compiler/swift_helpers.cc b/src/compiler/swift_helpers.cc index 4be20d3..599fa17 100644 --- a/src/compiler/swift_helpers.cc +++ b/src/compiler/swift_helpers.cc @@ -26,15 +26,15 @@ #include "google/protobuf/swift-descriptor.pb.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - namespace { - const string& FieldName(const FieldDescriptor* field) { - if (field->type() == FieldDescriptor::TYPE_GROUP) { - return field->message_type()->name(); - } else { - return field->name(); - } + namespace { + const string& FieldName(const FieldDescriptor* field) { + if (field->type() == FieldDescriptor::TYPE_GROUP) { + return field->message_type()->name(); + } else { + return field->name(); + } + } } - } string CheckReservedNames(const string& input) { @@ -51,213 +51,213 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { } return result; } - - + + string UnderscoresToCapitalizedCamelCase(const string& input) { - vector values; - string current; - - bool last_char_was_number = false; - bool last_char_was_lower = false; - bool last_char_was_upper = false; - for (unsigned int i = 0; i < input.size(); i++) { - char c = input[i]; - if (c >= '0' && c <= '9') { - if (!last_char_was_number) { - values.push_back(current); - current = ""; - } - current += c; - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_number = true; - } else if (c >= 'a' && c <= 'z') { - // lowercase letter can follow a lowercase or uppercase letter - if (!last_char_was_lower && !last_char_was_upper) { - values.push_back(current); - current = ""; - } - current += c; - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_lower = true; - } else if (c >= 'A' && c <= 'Z') { - if (!last_char_was_upper) { - values.push_back(current); - current = ""; - } - current += c; - last_char_was_number = last_char_was_lower = last_char_was_upper = false; - last_char_was_upper = true; - } else { - last_char_was_number = last_char_was_lower = last_char_was_upper = false; + vector values; + string current; + + bool last_char_was_number = false; + bool last_char_was_lower = false; + bool last_char_was_upper = false; + for (unsigned int i = 0; i < input.size(); i++) { + char c = input[i]; + if (c >= '0' && c <= '9') { + if (!last_char_was_number) { + values.push_back(current); + current = ""; + } + current += c; + last_char_was_number = last_char_was_lower = last_char_was_upper = false; + last_char_was_number = true; + } else if (c >= 'a' && c <= 'z') { + // lowercase letter can follow a lowercase or uppercase letter + if (!last_char_was_lower && !last_char_was_upper) { + values.push_back(current); + current = ""; + } + current += c; + last_char_was_number = last_char_was_lower = last_char_was_upper = false; + last_char_was_lower = true; + } else if (c >= 'A' && c <= 'Z') { + if (!last_char_was_upper) { + values.push_back(current); + current = ""; + } + current += c; + last_char_was_number = last_char_was_lower = last_char_was_upper = false; + last_char_was_upper = true; + } else { + last_char_was_number = last_char_was_lower = last_char_was_upper = false; + } } - } - values.push_back(current); - - for (vector::iterator i = values.begin(); i != values.end(); ++i) { - string value = *i; - for (unsigned int j = 0; j < value.length(); j++) { - if (j == 0) { - value[j] = toupper(value[j]); - } else { - value[j] = tolower(value[j]); - } + values.push_back(current); + + for (vector::iterator i = values.begin(); i != values.end(); ++i) { + string value = *i; + for (unsigned int j = 0; j < value.length(); j++) { + if (j == 0) { + value[j] = toupper(value[j]); + } else { + value[j] = tolower(value[j]); + } + } + *i = value; + } + string result; + for (vector::iterator i = values.begin(); i != values.end(); ++i) { + result += *i; } - *i = value; - } - string result; - for (vector::iterator i = values.begin(); i != values.end(); ++i) { - result += *i; - } - return CheckReservedNames(result); + return CheckReservedNames(result); } - - + + string UnderscoresToCamelCase(const string& input) { - string result = UnderscoresToCapitalizedCamelCase(input); - - if (result.length() == 0) { + string result = UnderscoresToCapitalizedCamelCase(input); + + if (result.length() == 0) { + return result; + } + + result[0] = tolower(result[0]); + return CheckReservedNames(result); + } + + + string UnderscoresToCamelCase(const FieldDescriptor* field) { + return UnderscoresToCamelCase(FieldName(field)); + } + + + string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { + return UnderscoresToCapitalizedCamelCase(FieldName(field)); + } + + + string UnderscoresToCamelCase(const MethodDescriptor* method) { + return UnderscoresToCamelCase(method->name()); + } + + + string FilenameToCamelCase(const string& filename) { + string result; + bool need_uppercase = true; + + result.reserve(filename.length()); + + for (string::const_iterator it(filename.begin()), itEnd(filename.end()); it != itEnd; ++it) { + const char c = *it; + + // Ignore undesirable characters. The good character must be + // uppercased, though. + if (!isalnum(c) && c != '_') { + need_uppercase = true; + continue; + } + + // If an uppercased character has been requested, transform the current + // character, append it to the result, reset the flag, and move on. + // This is safe to do even if the character is already uppercased. + if (need_uppercase && isalpha(c)) { + result += toupper(c); + need_uppercase = false; + continue; + } + + // Simply append this character. + result += c; + + // If this character was a digit, we want the next character to be an + // uppercased letter. + if (isdigit(c)) { + need_uppercase = true; + } + } + return result; - } - - result[0] = tolower(result[0]); - return CheckReservedNames(result); } - - - string UnderscoresToCamelCase(const FieldDescriptor* field) { - return UnderscoresToCamelCase(FieldName(field)); - } - - - string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field) { - return UnderscoresToCapitalizedCamelCase(FieldName(field)); - } - - - string UnderscoresToCamelCase(const MethodDescriptor* method) { - return UnderscoresToCamelCase(method->name()); - } - - - string FilenameToCamelCase(const string& filename) { - string result; - bool need_uppercase = true; - - result.reserve(filename.length()); - - for (string::const_iterator it(filename.begin()), itEnd(filename.end()); it != itEnd; ++it) { - const char c = *it; - - // Ignore undesirable characters. The good character must be - // uppercased, though. - if (!isalnum(c) && c != '_') { - need_uppercase = true; - continue; - } - - // If an uppercased character has been requested, transform the current - // character, append it to the result, reset the flag, and move on. - // This is safe to do even if the character is already uppercased. - if (need_uppercase && isalpha(c)) { - result += toupper(c); - need_uppercase = false; - continue; - } - - // Simply append this character. - result += c; - - // If this character was a digit, we want the next character to be an - // uppercased letter. - if (isdigit(c)) { - need_uppercase = true; - } + + + string StripProto(const string& filename) { + if (HasSuffixString(filename, ".protodevel")) { + return StripSuffixString(filename, ".protodevel"); + } else { + return StripSuffixString(filename, ".proto"); + } } - - return result; - } - - - string StripProto(const string& filename) { - if (HasSuffixString(filename, ".protodevel")) { - return StripSuffixString(filename, ".protodevel"); - } else { - return StripSuffixString(filename, ".proto"); + + bool IsBootstrapFile(const FileDescriptor* file) { + return file->name() == "google/protobuf/descriptor.proto"; } - } - - bool IsBootstrapFile(const FileDescriptor* file) { - return file->name() == "google/protobuf/descriptor.proto"; - } - - - string FileName(const FileDescriptor* file) { - string basename; - - string::size_type last_slash = file->name().find_last_of('/'); - if (last_slash == string::npos) { - basename += file->name(); - } else { - basename += file->name().substr(last_slash + 1); + + + string FileName(const FileDescriptor* file) { + string basename; + + string::size_type last_slash = file->name().find_last_of('/'); + if (last_slash == string::npos) { + basename += file->name(); + } else { + basename += file->name().substr(last_slash + 1); + } + + return FilenameToCamelCase(StripProto(basename)); } - - return FilenameToCamelCase(StripProto(basename)); - } - - - string FilePath(const FileDescriptor* file) { - string path = FileName(file); - - if (file->options().HasExtension(swift_file_options)) { - SwiftFileOptions options = file->options().GetExtension(swift_file_options); - - if (options.package() != "") { - path = options.package() + "/" + path; - } + + + string FilePath(const FileDescriptor* file) { + string path = FileName(file); + + if (file->options().HasExtension(swift_file_options)) { + SwiftFileOptions options = file->options().GetExtension(swift_file_options); + + if (options.package() != "") { + path = options.package() + "/" + path; + } + } + + return path; } - - return path; - } - - - string FileClassPrefix(const FileDescriptor* file) { - if (IsBootstrapFile(file)) { - return "PB"; - } else if (file->options().HasExtension(swift_file_options)) { - SwiftFileOptions options = file->options().GetExtension(swift_file_options); - - return options.class_prefix(); - } else { - return ""; + + + string FileClassPrefix(const FileDescriptor* file) { + if (IsBootstrapFile(file)) { + return "PB"; + } else if (file->options().HasExtension(swift_file_options)) { + SwiftFileOptions options = file->options().GetExtension(swift_file_options); + + return options.class_prefix(); + } else { + return ""; + } } - } - - - string FileClassName(const FileDescriptor* file) { - // Ensure the FileClassName is camelcased irrespective of whether the - // camelcase_output_filename option is set. - return FileClassPrefix(file) + + + + string FileClassName(const FileDescriptor* file) { + // Ensure the FileClassName is camelcased irrespective of whether the + // camelcase_output_filename option is set. + return FileClassPrefix(file) + UnderscoresToCapitalizedCamelCase(FileName(file)) + "Root"; - } - - - string ToSwiftName(const string& full_name, const FileDescriptor* file) { - string result; - result += FileClassPrefix(file); - result += full_name; - return result; - } - - - string ClassNameWorker(const Descriptor* descriptor) { - string name; - if (descriptor->containing_type() != NULL) { - name = ClassNameWorker(descriptor->containing_type()); - name += "."; - } - return CheckReservedNames(name + descriptor->name()); - } - + } + + + string ToSwiftName(const string& full_name, const FileDescriptor* file) { + string result; + result += FileClassPrefix(file); + result += full_name; + return result; + } + + + string ClassNameWorker(const Descriptor* descriptor) { + string name; + if (descriptor->containing_type() != NULL) { + name = ClassNameWorker(descriptor->containing_type()); + name += "."; + } + return CheckReservedNames(name + descriptor->name()); + } + string ClassNameWorkerExtensions(const Descriptor* descriptor) { string name; if (descriptor->containing_type() != NULL) { @@ -266,31 +266,31 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { } return CheckReservedNames(name + descriptor->name()); } - - - string ClassNameWorker(const EnumDescriptor* descriptor) { - string name; - if (descriptor->containing_type() != NULL) { - name = ClassNameWorker(descriptor->containing_type()); - name += "."; - } - return CheckReservedNames(name + UnderscoresToCapitalizedCamelCase(descriptor->name())); - } - - - string ClassName(const Descriptor* descriptor) { - string name; - name += FileClassPrefix(descriptor->file()); - name += ClassNameWorker(descriptor); - return CheckReservedNames(name); - } + + + string ClassNameWorker(const EnumDescriptor* descriptor) { + string name; + if (descriptor->containing_type() != NULL) { + name = ClassNameWorker(descriptor->containing_type()); + name += "."; + } + return CheckReservedNames(name + UnderscoresToCapitalizedCamelCase(descriptor->name())); + } + + + string ClassName(const Descriptor* descriptor) { + string name; + name += FileClassPrefix(descriptor->file()); + name += ClassNameWorker(descriptor); + return CheckReservedNames(name); + } string ClassNameExtensions(const Descriptor* descriptor) { string name; name += FileClassPrefix(descriptor->file()); name += ClassNameWorkerExtensions(descriptor); return CheckReservedNames(name); } - + string ClassNameMessage(const Descriptor* descriptor) { string name; name += FileClassPrefix(descriptor->file()); @@ -304,8 +304,8 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { } return CheckReservedNames(name); } - - + + string ClassNameOneof(const OneofDescriptor* descriptor) { string name; if (descriptor->containing_type() != NULL) { @@ -315,268 +315,268 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { return CheckReservedNames(name + UnderscoresToCapitalizedCamelCase(descriptor->name())); } - bool isOneOfField(const FieldDescriptor* descriptor) { - if (descriptor->containing_oneof()) - { - return true; - - } - return false; - } - - - string ClassName(const EnumDescriptor* descriptor) { - string name; - name += FileClassPrefix(descriptor->file()); - name += ClassNameWorker(descriptor); - return CheckReservedNames(name); - } - - - string ClassName(const ServiceDescriptor* descriptor) { - string name; - name += FileClassPrefix(descriptor->file()); - name += descriptor->name(); - return CheckReservedNames(name); - } - - - string EnumValueName(const EnumValueDescriptor* descriptor) { - return - UnderscoresToCapitalizedCamelCase(SafeName(descriptor->name())); - } - - - SwiftType GetSwiftType(FieldDescriptor::Type field_type) { - switch (field_type) { - case FieldDescriptor::TYPE_INT32: - case FieldDescriptor::TYPE_UINT32: - case FieldDescriptor::TYPE_SINT32: - case FieldDescriptor::TYPE_FIXED32: - case FieldDescriptor::TYPE_SFIXED32: - return SWIFTTYPE_INT; - - case FieldDescriptor::TYPE_INT64: - case FieldDescriptor::TYPE_UINT64: - case FieldDescriptor::TYPE_SINT64: - case FieldDescriptor::TYPE_FIXED64: - case FieldDescriptor::TYPE_SFIXED64: - return SWIFTTYPE_LONG; - - case FieldDescriptor::TYPE_FLOAT: - return SWIFTTYPE_FLOAT; - - case FieldDescriptor::TYPE_DOUBLE: - return SWIFTTYPE_DOUBLE; - - case FieldDescriptor::TYPE_BOOL: - return SWIFTTYPE_BOOLEAN; - - case FieldDescriptor::TYPE_STRING: - return SWIFTTYPE_STRING; - - case FieldDescriptor::TYPE_BYTES: - return SWIFTTYPE_DATA; - - case FieldDescriptor::TYPE_ENUM: - return SWIFTTYPE_ENUM; -// -// case FieldDescriptor::TYPE_ONEOF: -// return SWIFTTYPE_ONEOF; + bool isOneOfField(const FieldDescriptor* descriptor) { + if (descriptor->containing_oneof()) + { + return true; + + } + return false; + } + + + string ClassName(const EnumDescriptor* descriptor) { + string name; + name += FileClassPrefix(descriptor->file()); + name += ClassNameWorker(descriptor); + return CheckReservedNames(name); + } + + + string ClassName(const ServiceDescriptor* descriptor) { + string name; + name += FileClassPrefix(descriptor->file()); + name += descriptor->name(); + return CheckReservedNames(name); + } + + + string EnumValueName(const EnumValueDescriptor* descriptor) { + return + UnderscoresToCapitalizedCamelCase(SafeName(descriptor->name())); + } + + + SwiftType GetSwiftType(FieldDescriptor::Type field_type) { + switch (field_type) { + case FieldDescriptor::TYPE_INT32: + case FieldDescriptor::TYPE_UINT32: + case FieldDescriptor::TYPE_SINT32: + case FieldDescriptor::TYPE_FIXED32: + case FieldDescriptor::TYPE_SFIXED32: + return SWIFTTYPE_INT; + + case FieldDescriptor::TYPE_INT64: + case FieldDescriptor::TYPE_UINT64: + case FieldDescriptor::TYPE_SINT64: + case FieldDescriptor::TYPE_FIXED64: + case FieldDescriptor::TYPE_SFIXED64: + return SWIFTTYPE_LONG; + + case FieldDescriptor::TYPE_FLOAT: + return SWIFTTYPE_FLOAT; + + case FieldDescriptor::TYPE_DOUBLE: + return SWIFTTYPE_DOUBLE; + + case FieldDescriptor::TYPE_BOOL: + return SWIFTTYPE_BOOLEAN; + + case FieldDescriptor::TYPE_STRING: + return SWIFTTYPE_STRING; + + case FieldDescriptor::TYPE_BYTES: + return SWIFTTYPE_DATA; + + case FieldDescriptor::TYPE_ENUM: + return SWIFTTYPE_ENUM; + // + // case FieldDescriptor::TYPE_ONEOF: + // return SWIFTTYPE_ONEOF; + + case FieldDescriptor::TYPE_GROUP: + case FieldDescriptor::TYPE_MESSAGE: + return SWIFTTYPE_MESSAGE; + } - case FieldDescriptor::TYPE_GROUP: - case FieldDescriptor::TYPE_MESSAGE: - return SWIFTTYPE_MESSAGE; + GOOGLE_LOG(FATAL) << "Can't get here."; + return SWIFTTYPE_INT; } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return SWIFTTYPE_INT; - } - - - const char* BoxedPrimitiveTypeName(SwiftType type) { - switch (type) { - case SWIFTTYPE_INT : return "Int32"; - case SWIFTTYPE_LONG : return "Int64"; - case SWIFTTYPE_FLOAT : return "Float"; - case SWIFTTYPE_DOUBLE : return "Double"; - case SWIFTTYPE_BOOLEAN: return "Bool"; - case SWIFTTYPE_STRING : return "String"; - case SWIFTTYPE_DATA : return "[Byte]"; - case SWIFTTYPE_ENUM : return "Int32"; - case SWIFTTYPE_MESSAGE: return NULL; + + + const char* BoxedPrimitiveTypeName(SwiftType type) { + switch (type) { + case SWIFTTYPE_INT : return "Int32"; + case SWIFTTYPE_LONG : return "Int64"; + case SWIFTTYPE_FLOAT : return "Float"; + case SWIFTTYPE_DOUBLE : return "Double"; + case SWIFTTYPE_BOOLEAN: return "Bool"; + case SWIFTTYPE_STRING : return "String"; + case SWIFTTYPE_DATA : return "[Byte]"; + case SWIFTTYPE_ENUM : return "Int32"; + case SWIFTTYPE_MESSAGE: return NULL; + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; - } - - - bool IsPrimitiveType(SwiftType type) { - switch (type) { - case SWIFTTYPE_INT : - case SWIFTTYPE_LONG : - case SWIFTTYPE_FLOAT : - case SWIFTTYPE_DOUBLE : - case SWIFTTYPE_BOOLEAN: - case SWIFTTYPE_ENUM : - return true; - - default: - return false; + + + bool IsPrimitiveType(SwiftType type) { + switch (type) { + case SWIFTTYPE_INT : + case SWIFTTYPE_LONG : + case SWIFTTYPE_FLOAT : + case SWIFTTYPE_DOUBLE : + case SWIFTTYPE_BOOLEAN: + case SWIFTTYPE_ENUM : + return true; + + default: + return false; + } } - } - - - bool IsReferenceType(SwiftType type) { - return !IsPrimitiveType(type); - } - - - bool ReturnsPrimitiveType(const FieldDescriptor* field) { - return IsPrimitiveType(GetSwiftType(field->type())); - } - - - bool ReturnsReferenceType(const FieldDescriptor* field) { - return !ReturnsPrimitiveType(field); - } - - - namespace { - string DotsToUnderscores(const string& name) { - return StringReplace(name, ".", "_", true); + + + bool IsReferenceType(SwiftType type) { + return !IsPrimitiveType(type); } - - const char* const kKeywordList[] = { - "TYPE_BOOL" - }; - - - hash_set MakeKeywordsMap() { - hash_set result; - for (unsigned int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) { - result.insert(kKeywordList[i]); - } - return result; + + + bool ReturnsPrimitiveType(const FieldDescriptor* field) { + return IsPrimitiveType(GetSwiftType(field->type())); } - - hash_set kKeywords = MakeKeywordsMap(); - } - - - string SafeName(const string& name) { - string result = name; - if (kKeywords.count(result) > 0) { - result.append("_"); + + + bool ReturnsReferenceType(const FieldDescriptor* field) { + return !ReturnsPrimitiveType(field); } - return result; - } - - bool AllAscii(const string& text) { - for (unsigned int i = 0; i < text.size(); i++) { - if ((text[i] & 0x80) != 0) { - return false; - } + + + namespace { + string DotsToUnderscores(const string& name) { + return StringReplace(name, ".", "_", true); + } + + const char* const kKeywordList[] = { + "TYPE_BOOL" + }; + + + hash_set MakeKeywordsMap() { + hash_set result; + for (unsigned int i = 0; i < GOOGLE_ARRAYSIZE(kKeywordList); i++) { + result.insert(kKeywordList[i]); + } + return result; + } + + hash_set kKeywords = MakeKeywordsMap(); } - return true; - } - - string DefaultValue(const FieldDescriptor* field) { - // Switch on cpp_type since we need to know which default_value_* method - // of FieldDescriptor to call. - switch (field->cpp_type()) { - case FieldDescriptor::CPPTYPE_INT32: return "Int32(" + SimpleItoa(field->default_value_int32()) +")"; - case FieldDescriptor::CPPTYPE_UINT32: return "UInt32(" + SimpleItoa(field->default_value_uint32()) + ")"; - case FieldDescriptor::CPPTYPE_INT64: return "Int64(" + SimpleItoa(field->default_value_int64()) + ")"; - case FieldDescriptor::CPPTYPE_UINT64: return "UInt64(" + SimpleItoa(field->default_value_uint64()) + ")"; - case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool() ? "true" : "false"; - case FieldDescriptor::CPPTYPE_DOUBLE: { - const double value = field->default_value_double(); - if (value == numeric_limits::infinity()) { - return "Double(HUGE)"; - } else if (value == -numeric_limits::infinity()) { - return "Double(-HUGE)"; - } else if (value != value) { - return "0.0"; - } else { - return "Double("+ SimpleDtoa(field->default_value_double()) + ")"; - } + + + string SafeName(const string& name) { + string result = name; + if (kKeywords.count(result) > 0) { + result.append("_"); } - case FieldDescriptor::CPPTYPE_FLOAT: { - const float value = field->default_value_float(); - if (value == numeric_limits::infinity()) { - return "HUGE"; - } else if (value == -numeric_limits::infinity()) { - return "-HUGE"; - } else if (value != value) { - return "0.0"; - } else { - return "Float(" + SimpleFtoa(value) + ")"; - } + return result; + } + + bool AllAscii(const string& text) { + for (unsigned int i = 0; i < text.size(); i++) { + if ((text[i] & 0x80) != 0) { + return false; + } } - case FieldDescriptor::CPPTYPE_STRING: - if (field->type() == FieldDescriptor::TYPE_BYTES) { - if (field->has_default_value()) { - return - "([Byte]() + \"" + CEscape(field->default_value_string()) + "\".utf8)"; - } else { - return "[Byte]()"; + return true; + } + + string DefaultValue(const FieldDescriptor* field) { + // Switch on cpp_type since we need to know which default_value_* method + // of FieldDescriptor to call. + switch (field->cpp_type()) { + case FieldDescriptor::CPPTYPE_INT32: return "Int32(" + SimpleItoa(field->default_value_int32()) +")"; + case FieldDescriptor::CPPTYPE_UINT32: return "UInt32(" + SimpleItoa(field->default_value_uint32()) + ")"; + case FieldDescriptor::CPPTYPE_INT64: return "Int64(" + SimpleItoa(field->default_value_int64()) + ")"; + case FieldDescriptor::CPPTYPE_UINT64: return "UInt64(" + SimpleItoa(field->default_value_uint64()) + ")"; + case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool() ? "true" : "false"; + case FieldDescriptor::CPPTYPE_DOUBLE: { + const double value = field->default_value_double(); + if (value == numeric_limits::infinity()) { + return "Double(HUGE)"; + } else if (value == -numeric_limits::infinity()) { + return "Double(-HUGE)"; + } else if (value != value) { + return "0.0"; + } else { + return "Double("+ SimpleDtoa(field->default_value_double()) + ")"; + } } - } else { - if (AllAscii(field->default_value_string())) { - return "\"" + EscapeTrigraphs(CEscape(EscapeUnicode(field->default_value_string()))) + "\""; - } else { - return "\"" + EscapeTrigraphs(CEscape(EscapeUnicode(field->default_value_string()))) + "\""; + case FieldDescriptor::CPPTYPE_FLOAT: { + const float value = field->default_value_float(); + if (value == numeric_limits::infinity()) { + return "HUGE"; + } else if (value == -numeric_limits::infinity()) { + return "-HUGE"; + } else if (value != value) { + return "0.0"; + } else { + return "Float(" + SimpleFtoa(value) + ")"; + } } - } - case FieldDescriptor::CPPTYPE_ENUM: - return EnumValueName(field->default_value_enum()); - case FieldDescriptor::CPPTYPE_MESSAGE: - return ClassName(field->message_type()) + "()"; + case FieldDescriptor::CPPTYPE_STRING: + if (field->type() == FieldDescriptor::TYPE_BYTES) { + if (field->has_default_value()) { + return + "([Byte]() + \"" + CEscape(field->default_value_string()) + "\".utf8)"; + } else { + return "[Byte]()"; + } + } else { + if (AllAscii(field->default_value_string())) { + return "\"" + EscapeTrigraphs(CEscape(EscapeUnicode(field->default_value_string()))) + "\""; + } else { + return "\"" + EscapeTrigraphs(CEscape(EscapeUnicode(field->default_value_string()))) + "\""; + } + } + case FieldDescriptor::CPPTYPE_ENUM: + return EnumValueName(field->default_value_enum()); + case FieldDescriptor::CPPTYPE_MESSAGE: + return ClassName(field->message_type()) + "()"; + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return ""; } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return ""; - } - -// const char* GetArrayValueType(const FieldDescriptor* field) { -// switch (field->type()) { -// case FieldDescriptor::TYPE_INT32 : return "Int32" ; -// case FieldDescriptor::TYPE_UINT32 : return "UInt32"; -// case FieldDescriptor::TYPE_SINT32 : return "Int32" ; -// case FieldDescriptor::TYPE_FIXED32 : return "UInt32"; -// case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; -// case FieldDescriptor::TYPE_INT64 : return "Int64" ; -// case FieldDescriptor::TYPE_UINT64 : return "UInt64"; -// case FieldDescriptor::TYPE_SINT64 : return "Int64" ; -// case FieldDescriptor::TYPE_FIXED64 : return "UInt64"; -// case FieldDescriptor::TYPE_SFIXED64: return "PBArrayValueTypeInt64" ; -// case FieldDescriptor::TYPE_FLOAT : return "PBArrayValueTypeFloat" ; -// case FieldDescriptor::TYPE_DOUBLE : return "PBArrayValueTypeDouble"; -// case FieldDescriptor::TYPE_BOOL : return "PBArrayValueTypeBool" ; -// case FieldDescriptor::TYPE_STRING : return "PBArrayValueTypeObject"; -// case FieldDescriptor::TYPE_BYTES : return "PBArrayValueTypeObject"; -// case FieldDescriptor::TYPE_ENUM : return "PBArrayValueTypeObject"; -// case FieldDescriptor::TYPE_GROUP : return "PBArrayValueTypeObject"; -// case FieldDescriptor::TYPE_MESSAGE : return "PBArrayValueTypeObject"; -// } -// -// GOOGLE_LOG(FATAL) << "Can't get here."; -// return NULL; -// } - - // Escape C++ trigraphs by escaping question marks to \? - + + // const char* GetArrayValueType(const FieldDescriptor* field) { + // switch (field->type()) { + // case FieldDescriptor::TYPE_INT32 : return "Int32" ; + // case FieldDescriptor::TYPE_UINT32 : return "UInt32"; + // case FieldDescriptor::TYPE_SINT32 : return "Int32" ; + // case FieldDescriptor::TYPE_FIXED32 : return "UInt32"; + // case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; + // case FieldDescriptor::TYPE_INT64 : return "Int64" ; + // case FieldDescriptor::TYPE_UINT64 : return "UInt64"; + // case FieldDescriptor::TYPE_SINT64 : return "Int64" ; + // case FieldDescriptor::TYPE_FIXED64 : return "UInt64"; + // case FieldDescriptor::TYPE_SFIXED64: return "PBArrayValueTypeInt64" ; + // case FieldDescriptor::TYPE_FLOAT : return "PBArrayValueTypeFloat" ; + // case FieldDescriptor::TYPE_DOUBLE : return "PBArrayValueTypeDouble"; + // case FieldDescriptor::TYPE_BOOL : return "PBArrayValueTypeBool" ; + // case FieldDescriptor::TYPE_STRING : return "PBArrayValueTypeObject"; + // case FieldDescriptor::TYPE_BYTES : return "PBArrayValueTypeObject"; + // case FieldDescriptor::TYPE_ENUM : return "PBArrayValueTypeObject"; + // case FieldDescriptor::TYPE_GROUP : return "PBArrayValueTypeObject"; + // case FieldDescriptor::TYPE_MESSAGE : return "PBArrayValueTypeObject"; + // } + // + // GOOGLE_LOG(FATAL) << "Can't get here."; + // return NULL; + // } + + // Escape C++ trigraphs by escaping question marks to \? + string EscapeTrigraphs(const string& to_escape) { return StringReplace(to_escape, "?", "\\?", true); } string EscapeUnicode(const string& to_escape) { return to_escape;//StringReplace(to_escape, "\", "", true); - + } - + } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_helpers.h b/src/compiler/swift_helpers.h index 13f42fe..145eda5 100644 --- a/src/compiler/swift_helpers.h +++ b/src/compiler/swift_helpers.h @@ -23,119 +23,119 @@ #include namespace google { -namespace protobuf { -namespace compiler { -namespace swift { - -string CheckReservedNames(const string& input); -// Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes -// "fooBarBaz" or "FooBarBaz", respectively. -string UnderscoresToCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); -string UnderscoresToCapitalizedCamelCase(const string& name); - -// Similar, but for method names. (Typically, this merely has the effect -// of lower-casing the first letter of the name.) -string UnderscoresToCamelCase(const MethodDescriptor* method); - -// Apply CamelCase-formatting to the given filename string. Existing -// capitalization is not modified, but non-alphanumeric characters are -// removed and the following legal character is capitalized. -string FilenameToCamelCase(const string& filename); - -// Strips ".proto" or ".protodevel" from the end of a filename. -string StripProto(const string& filename); - -// Returns true if the name requires a ns_returns_not_retained attribute applied -// to it. - -bool IsBootstrapFile(const FileDescriptor* file); - - -// Gets the name of the file we're going to generate (sans the .pb.h -// extension). This does not include the path to that file. -string FileName(const FileDescriptor* file); - -// Gets the path of the file we're going to generate (sans the .pb.h -// extension). The path will be dependent on the swift package -// declared in the proto package. -string FilePath(const FileDescriptor* file); - -// Gets the name of the root class we'll generate in the file. This class -// is not meant for external consumption, but instead contains helpers that -// the rest of the the classes need -string FileClassName(const FileDescriptor* file); - -// These return the fully-qualified class name corresponding to the given -// descriptor. -string ClassName(const Descriptor* descriptor); -string ClassName(const EnumDescriptor* descriptor); -string ClassName(const ServiceDescriptor* descriptor); -string ClassNameMessage(const Descriptor* descriptor); -string ClassNameExtensions(const Descriptor* descriptor); -string ClassNameOneof(const OneofDescriptor* descriptor); -string EnumValueName(const EnumValueDescriptor* descriptor); - -string SafeName(const string& name); - -enum SwiftType { - SWIFTTYPE_INT, - SWIFTTYPE_LONG, - SWIFTTYPE_FLOAT, - SWIFTTYPE_DOUBLE, - SWIFTTYPE_BOOLEAN, - SWIFTTYPE_STRING, - SWIFTTYPE_DATA, - SWIFTTYPE_ENUM, -// SWIFTTYPE_ONEOF, - SWIFTTYPE_MESSAGE -}; - -SwiftType GetSwiftType(FieldDescriptor::Type field_type); - -inline SwiftType GetSwiftType(const FieldDescriptor* field) { - return GetSwiftType(field->type()); -} - -// Get the fully-qualified class name for a boxed primitive type, e.g. -// "NSNumber" for SWIFTTYPE_INT. Returns NULL for enum and message -// types. -const char* BoxedPrimitiveTypeName(SwiftType type); - -bool IsPrimitiveType(SwiftType type); -bool IsReferenceType(SwiftType type); -bool isOneOfField(const FieldDescriptor* descriptor); - -bool ReturnsPrimitiveType(const FieldDescriptor* field); -bool ReturnsReferenceType(const FieldDescriptor* field); - -string DefaultValue(const FieldDescriptor* field); - -//const char* GetArrayValueType(const FieldDescriptor* field); - -// Escape C++ trigraphs by escaping question marks to \? -string EscapeTrigraphs(const string& to_escape); -string EscapeUnicode(const string& to_escape); - -// Do message classes in this file keep track of unknown fields? -inline bool HasUnknownFields(const FileDescriptor *file) { - return file->options().optimize_for() != FileOptions::LITE_RUNTIME; -} - -// Does this file have generated parsing, serialization, and other -// standard methods for which reflection-based fallback implementations exist? -inline bool HasGeneratedMethods(const FileDescriptor *file) { - return file->options().optimize_for() != FileOptions::CODE_SIZE; -} - -// Do message classes in this file have descriptor and refelction methods? -inline bool HasDescriptorMethods(const FileDescriptor *file) { - return file->options().optimize_for() != FileOptions::LITE_RUNTIME; -} - -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace compiler { + namespace swift { + + string CheckReservedNames(const string& input); + // Converts the field's name to camel-case, e.g. "foo_bar_baz" becomes + // "fooBarBaz" or "FooBarBaz", respectively. + string UnderscoresToCamelCase(const FieldDescriptor* field); + string UnderscoresToCapitalizedCamelCase(const FieldDescriptor* field); + string UnderscoresToCapitalizedCamelCase(const string& name); + + // Similar, but for method names. (Typically, this merely has the effect + // of lower-casing the first letter of the name.) + string UnderscoresToCamelCase(const MethodDescriptor* method); + + // Apply CamelCase-formatting to the given filename string. Existing + // capitalization is not modified, but non-alphanumeric characters are + // removed and the following legal character is capitalized. + string FilenameToCamelCase(const string& filename); + + // Strips ".proto" or ".protodevel" from the end of a filename. + string StripProto(const string& filename); + + // Returns true if the name requires a ns_returns_not_retained attribute applied + // to it. + + bool IsBootstrapFile(const FileDescriptor* file); + + + // Gets the name of the file we're going to generate (sans the .pb.h + // extension). This does not include the path to that file. + string FileName(const FileDescriptor* file); + + // Gets the path of the file we're going to generate (sans the .pb.h + // extension). The path will be dependent on the swift package + // declared in the proto package. + string FilePath(const FileDescriptor* file); + + // Gets the name of the root class we'll generate in the file. This class + // is not meant for external consumption, but instead contains helpers that + // the rest of the the classes need + string FileClassName(const FileDescriptor* file); + + // These return the fully-qualified class name corresponding to the given + // descriptor. + string ClassName(const Descriptor* descriptor); + string ClassName(const EnumDescriptor* descriptor); + string ClassName(const ServiceDescriptor* descriptor); + string ClassNameMessage(const Descriptor* descriptor); + string ClassNameExtensions(const Descriptor* descriptor); + string ClassNameOneof(const OneofDescriptor* descriptor); + string EnumValueName(const EnumValueDescriptor* descriptor); + + string SafeName(const string& name); + + enum SwiftType { + SWIFTTYPE_INT, + SWIFTTYPE_LONG, + SWIFTTYPE_FLOAT, + SWIFTTYPE_DOUBLE, + SWIFTTYPE_BOOLEAN, + SWIFTTYPE_STRING, + SWIFTTYPE_DATA, + SWIFTTYPE_ENUM, + // SWIFTTYPE_ONEOF, + SWIFTTYPE_MESSAGE + }; + + SwiftType GetSwiftType(FieldDescriptor::Type field_type); + + inline SwiftType GetSwiftType(const FieldDescriptor* field) { + return GetSwiftType(field->type()); + } + + // Get the fully-qualified class name for a boxed primitive type, e.g. + // "NSNumber" for SWIFTTYPE_INT. Returns NULL for enum and message + // types. + const char* BoxedPrimitiveTypeName(SwiftType type); + + bool IsPrimitiveType(SwiftType type); + bool IsReferenceType(SwiftType type); + bool isOneOfField(const FieldDescriptor* descriptor); + + bool ReturnsPrimitiveType(const FieldDescriptor* field); + bool ReturnsReferenceType(const FieldDescriptor* field); + + string DefaultValue(const FieldDescriptor* field); + + //const char* GetArrayValueType(const FieldDescriptor* field); + + // Escape C++ trigraphs by escaping question marks to \? + string EscapeTrigraphs(const string& to_escape); + string EscapeUnicode(const string& to_escape); + + // Do message classes in this file keep track of unknown fields? + inline bool HasUnknownFields(const FileDescriptor *file) { + return file->options().optimize_for() != FileOptions::LITE_RUNTIME; + } + + // Does this file have generated parsing, serialization, and other + // standard methods for which reflection-based fallback implementations exist? + inline bool HasGeneratedMethods(const FileDescriptor *file) { + return file->options().optimize_for() != FileOptions::CODE_SIZE; + } + + // Do message classes in this file have descriptor and refelction methods? + inline bool HasDescriptorMethods(const FileDescriptor *file) { + return file->options().optimize_for() != FileOptions::LITE_RUNTIME; + } + + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_HELPERS_H diff --git a/src/compiler/swift_message.cc b/src/compiler/swift_message.cc index 6e15217..154c601 100644 --- a/src/compiler/swift_message.cc +++ b/src/compiler/swift_message.cc @@ -32,161 +32,161 @@ #include "swift_oneof.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - using internal::WireFormat; - using internal::WireFormatLite; - - namespace { - struct FieldOrderingByNumber { - inline bool operator()(const FieldDescriptor* a, - const FieldDescriptor* b) const { - return a->number() < b->number(); - } - }; - - struct FieldOrderingByType { - inline bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const { - if (a->is_repeated() != b->is_repeated()) { - return b->is_repeated(); - } - - - if (a->type() == FieldDescriptor::TYPE_BOOL && - b->type() != FieldDescriptor::TYPE_BOOL) { - return true; - } - - if (a->type() != FieldDescriptor::TYPE_BOOL && - b->type() == FieldDescriptor::TYPE_BOOL) { - return false; + + using internal::WireFormat; + using internal::WireFormatLite; + + namespace { + struct FieldOrderingByNumber { + inline bool operator()(const FieldDescriptor* a, + const FieldDescriptor* b) const { + return a->number() < b->number(); + } + }; + + struct FieldOrderingByType { + inline bool operator()(const FieldDescriptor* a, const FieldDescriptor* b) const { + if (a->is_repeated() != b->is_repeated()) { + return b->is_repeated(); + } + + + if (a->type() == FieldDescriptor::TYPE_BOOL && + b->type() != FieldDescriptor::TYPE_BOOL) { + return true; + } + + if (a->type() != FieldDescriptor::TYPE_BOOL && + b->type() == FieldDescriptor::TYPE_BOOL) { + return false; + } + + return a->type() < b->type(); + } + }; + + struct ExtensionRangeOrdering { + bool operator()(const Descriptor::ExtensionRange* a, + const Descriptor::ExtensionRange* b) const { + return a->start < b->start; + } + }; + + const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { + const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()]; + for (int i = 0; i < descriptor->field_count(); i++) { + fields[i] = descriptor->field(i); + } + sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber()); + return fields; } - - return a->type() < b->type(); - } - }; - - struct ExtensionRangeOrdering { - bool operator()(const Descriptor::ExtensionRange* a, - const Descriptor::ExtensionRange* b) const { - return a->start < b->start; - } - }; - - const FieldDescriptor** SortFieldsByNumber(const Descriptor* descriptor) { - const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()]; - for (int i = 0; i < descriptor->field_count(); i++) { - fields[i] = descriptor->field(i); - } - sort(fields, fields + descriptor->field_count(), FieldOrderingByNumber()); - return fields; - } - - const FieldDescriptor** SortFieldsByType(const Descriptor* descriptor) { - const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()]; - for (int i = 0; i < descriptor->field_count(); i++) { - - fields[i] = descriptor->field(i); - - } - sort(fields, fields + descriptor->field_count(), FieldOrderingByType()); - return fields; - } - string UniqueFileScopeIdentifier(const Descriptor* descriptor) { - return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); - } - - static bool HasRequiredFields( - const Descriptor* type, - hash_set* already_seen) { - if (already_seen->count(type) > 0) { - return false; + + const FieldDescriptor** SortFieldsByType(const Descriptor* descriptor) { + const FieldDescriptor** fields = new const FieldDescriptor*[descriptor->field_count()]; + for (int i = 0; i < descriptor->field_count(); i++) { + + fields[i] = descriptor->field(i); + + } + sort(fields, fields + descriptor->field_count(), FieldOrderingByType()); + return fields; } - already_seen->insert(type); - if (type->extension_range_count() > 0) { - return true; + string UniqueFileScopeIdentifier(const Descriptor* descriptor) { + return "static_" + StringReplace(descriptor->full_name(), ".", "_", true); } - - for (int i = 0; i < type->field_count(); i++) { - const FieldDescriptor* field = type->field(i); - if (field->is_required()) { - return true; - } - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { - if (HasRequiredFields(field->message_type(), already_seen)) { - return true; + + static bool HasRequiredFields( + const Descriptor* type, + hash_set* already_seen) { + if (already_seen->count(type) > 0) { + return false; + } + already_seen->insert(type); + if (type->extension_range_count() > 0) { + return true; } - } + + for (int i = 0; i < type->field_count(); i++) { + const FieldDescriptor* field = type->field(i); + if (field->is_required()) { + return true; + } + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { + if (HasRequiredFields(field->message_type(), already_seen)) { + return true; + } + } + } + + return false; } - - return false; - } - - static bool HasRequiredFields(const Descriptor* type) { - hash_set already_seen; - return HasRequiredFields(type, &already_seen); - } - } // namespace - - - MessageGenerator::MessageGenerator(const Descriptor* descriptor) + + static bool HasRequiredFields(const Descriptor* type) { + hash_set already_seen; + return HasRequiredFields(type, &already_seen); + } + } // namespace + + + MessageGenerator::MessageGenerator(const Descriptor* descriptor) : descriptor_(descriptor), field_generators_(descriptor) { - } - - - MessageGenerator::~MessageGenerator() { - } - - -// void MessageGenerator::GenerateStaticVariablesHeader(io::Printer* printer) { -// map vars; -// vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); -// vars["index"] = SimpleItoa(descriptor_->index()); -// vars["classname"] = ClassName(descriptor_); -// if (descriptor_->containing_type() != NULL) { -// vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); -// } -// -// for (int i = 0; i < descriptor_->nested_type_count(); i++) { -// MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesHeader(printer); -// } -// } - - - void MessageGenerator::GenerateStaticVariablesInitialization(io::Printer* printer) { - map vars; - vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); - vars["classname"] = ClassName(descriptor_); - if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); - } - - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateInitializationSource(printer); } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesInitialization(printer); + + + MessageGenerator::~MessageGenerator() { } - } - - - void MessageGenerator::GenerateStaticVariablesSource(io::Printer* printer) { - map vars; - vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); - vars["index"] = SimpleItoa(descriptor_->index()); - vars["classname"] = ClassName(descriptor_); - if (descriptor_->containing_type() != NULL) { - vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); + + + // void MessageGenerator::GenerateStaticVariablesHeader(io::Printer* printer) { + // map vars; + // vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); + // vars["index"] = SimpleItoa(descriptor_->index()); + // vars["classname"] = ClassName(descriptor_); + // if (descriptor_->containing_type() != NULL) { + // vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); + // } + // + // for (int i = 0; i < descriptor_->nested_type_count(); i++) { + // MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesHeader(printer); + // } + // } + + + void MessageGenerator::GenerateStaticVariablesInitialization(io::Printer* printer) { + map vars; + vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); + vars["index"] = SimpleItoa(descriptor_->index()); + vars["classname"] = ClassName(descriptor_); + if (descriptor_->containing_type() != NULL) { + vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); + } + + for (int i = 0; i < descriptor_->extension_count(); i++) { + ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateInitializationSource(printer); + } + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesInitialization(printer); + } } - - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateFieldsSource(printer); + + + void MessageGenerator::GenerateStaticVariablesSource(io::Printer* printer) { + map vars; + vars["identifier"] = UniqueFileScopeIdentifier(descriptor_); + vars["index"] = SimpleItoa(descriptor_->index()); + vars["classname"] = ClassName(descriptor_); + if (descriptor_->containing_type() != NULL) { + vars["parent"] = UniqueFileScopeIdentifier(descriptor_->containing_type()); + } + + for (int i = 0; i < descriptor_->extension_count(); i++) { + ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateFieldsSource(printer); + } + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesSource(printer); + } } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator(descriptor_->nested_type(i)).GenerateStaticVariablesSource(printer); - } - } void MessageGenerator::GenerateGlobalStaticVariablesSource(io::Printer* printer, string rootclass) { map vars; @@ -203,403 +203,403 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { MessageGenerator(descriptor_->nested_type(i)).GenerateGlobalStaticVariablesSource(printer, rootclass); } } - - - void MessageGenerator::DetermineDependencies(set* dependencies) { - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - - MessageGenerator(descriptor_->nested_type(i)).DetermineDependencies(dependencies); - } - } - - - void MessageGenerator::GenerateExtensionRegistrationSource(io::Printer* printer) { - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)) - .GenerateRegistrationSource(printer); - } - - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator(descriptor_->nested_type(i)) - .GenerateExtensionRegistrationSource(printer); - } - } - - - void MessageGenerator::GenerateSource(io::Printer* printer) { - - scoped_array sorted_fields(SortFieldsByType(descriptor_)); - - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "final public class $classname$ : ExtendableMessage {\n", - "classname", ClassNameMessage(descriptor_)); - } else { - printer->Print( - "final public class $classname$ : GeneratedMessage {\n", - "classname", ClassNameMessage(descriptor_)); - } - printer->Indent(); - - - //Nested Types - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - printer->Print("\n\n//Nested type declaration start\n\n"); - printer->Indent(); - MessageGenerator(descriptor_->nested_type(i)).GenerateSource(printer); - printer->Outdent(); - printer->Print("\n\n//Nested type declaration end\n\n"); - - } - - /// - - //Oneof - - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - OneofGenerator(descriptor_->oneof_decl(i)).GenerateSource(printer); - printer->Print("private var storage$storageName$:$classname$ = $classname$.$storageName$OneOfNotSet\n", - "storageName", UnderscoresToCapitalizedCamelCase(descriptor_->oneof_decl(i)->name()), - "classname", ClassNameOneof(descriptor_->oneof_decl(i))); - - } - - //// - - - ///Enums - - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - - printer->Indent(); - EnumGenerator(descriptor_->enum_type(i)).GenerateSource(printer); - printer->Outdent(); - - } - - - - - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateSynthesizeSource(printer); - } - - - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateMembersSource(printer); - } - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateMembersSource(printer); - } - - printer->Print("required public init() {\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateInitializationSource(printer); + void MessageGenerator::DetermineDependencies(set* dependencies) { + + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + + MessageGenerator(descriptor_->nested_type(i)).DetermineDependencies(dependencies); + } } - printer->Print(" super.init()\n" - "}\n"); - - - GenerateIsInitializedSource(printer); - GenerateMessageSerializationMethodsSource(printer); - - GenerateParseFromMethodsSource(printer); - - printer->Print( - "class func builder() -> $classname$Builder {\n" - " return $classname$Builder()\n" - "}\n" - "class func builderWithPrototype(prototype:$classname$) -> $classname$Builder {\n" - " return $classname$.builder().mergeFrom(prototype)\n" - "}\n" - "func builder() -> $classname$Builder {\n" - " return $classname$.builder()\n" - "}\n" - "func toBuilder() -> $classname$Builder {\n" - " return $classname$.builderWithPrototype(self)\n" - "}\n", - "classname", ClassName(descriptor_)); - - GenerateMessageDescriptionSource(printer); - - - GenerateMessageHashSource(printer); - //Meta informations - printer->Print("\n\n//Meta information declaration start\n\n"); - - printer->Print("override public class func className() -> String {\n" - " return \"$classname$\"\n" - "}\n", - "classname", - ClassName(descriptor_)); - - printer->Print("override public func classMetaType() -> GeneratedMessage.Type {\n" - " return $classname$.self\n" - "}\n", - "classname", - ClassName(descriptor_)); - - printer->Print("\n\n//Meta information declaration end\n\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - GenerateBuilderSource(printer); - } - - - void MessageGenerator::GenerateMessageSerializationMethodsSource(io::Printer* printer) { - scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); - - vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); + void MessageGenerator::GenerateExtensionRegistrationSource(io::Printer* printer) { + for (int i = 0; i < descriptor_->extension_count(); i++) { + ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)) + .GenerateRegistrationSource(printer); + } + + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + MessageGenerator(descriptor_->nested_type(i)) + .GenerateExtensionRegistrationSource(printer); + } } - sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "override public func writeToCodedOutputStream(output:CodedOutputStream) {\n"); - printer->Indent(); - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size(); ) { - if (i == descriptor_->field_count()) { - GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateSerializeOneFieldSource(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateSerializeOneFieldSource(printer, sorted_fields[i++]); + + + void MessageGenerator::GenerateSource(io::Printer* printer) { + + scoped_array sorted_fields(SortFieldsByType(descriptor_)); + + + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "final public class $classname$ : ExtendableMessage {\n", + "classname", ClassNameMessage(descriptor_)); } else { - GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]); + printer->Print( + "final public class $classname$ : GeneratedMessage {\n", + "classname", ClassNameMessage(descriptor_)); } - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "unknownFields.writeAsMessageSetTo(output)\n"); - } else { - printer->Print( - "unknownFields.writeToCodedOutputStream(output)\n"); - } - printer->Outdent(); - - printer->Print("}\n"); - - printer->Print("override public func serializedSize() -> Int32 {\n"); - printer->Indent(); - printer->Print("var size:Int32 = memoizedSerializedSize\n" - "if size != -1 {\n" - " return size\n" - "}\n" - "\n" - "size = 0\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCodeSource(printer); + printer->Indent(); + + + //Nested Types + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + printer->Print("\n\n//Nested type declaration start\n\n"); + printer->Indent(); + MessageGenerator(descriptor_->nested_type(i)).GenerateSource(printer); + printer->Outdent(); + printer->Print("\n\n//Nested type declaration end\n\n"); + + } + + /// + + //Oneof + + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + OneofGenerator(descriptor_->oneof_decl(i)).GenerateSource(printer); + printer->Print("private var storage$storageName$:$classname$ = $classname$.$storageName$OneOfNotSet\n", + "storageName", UnderscoresToCapitalizedCamelCase(descriptor_->oneof_decl(i)->name()), + "classname", ClassNameOneof(descriptor_->oneof_decl(i))); + + } + + //// + + + ///Enums + + for (int i = 0; i < descriptor_->enum_type_count(); i++) { + + printer->Indent(); + EnumGenerator(descriptor_->enum_type(i)).GenerateSource(printer); + printer->Outdent(); + + } + + + + + + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateSynthesizeSource(printer); + } + + + for (int i = 0; i < descriptor_->extension_count(); i++) { + ExtensionGenerator(ClassNameExtensions(descriptor_), descriptor_->extension(i)).GenerateMembersSource(printer); + } + + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateMembersSource(printer); + } + + printer->Print("required public init() {\n"); + + + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateInitializationSource(printer); + } + + + printer->Print(" super.init()\n" + "}\n"); + + + GenerateIsInitializedSource(printer); + GenerateMessageSerializationMethodsSource(printer); + + GenerateParseFromMethodsSource(printer); + + printer->Print( + "class func builder() -> $classname$Builder {\n" + " return $classname$Builder()\n" + "}\n" + "class func builderWithPrototype(prototype:$classname$) -> $classname$Builder {\n" + " return $classname$.builder().mergeFrom(prototype)\n" + "}\n" + "func builder() -> $classname$Builder {\n" + " return $classname$.builder()\n" + "}\n" + "func toBuilder() -> $classname$Builder {\n" + " return $classname$.builderWithPrototype(self)\n" + "}\n", + "classname", ClassName(descriptor_)); + + GenerateMessageDescriptionSource(printer); + + + GenerateMessageHashSource(printer); + //Meta informations + printer->Print("\n\n//Meta information declaration start\n\n"); + + printer->Print("override public class func className() -> String {\n" + " return \"$classname$\"\n" + "}\n", + "classname", + ClassName(descriptor_)); + + printer->Print("override public func classMetaType() -> GeneratedMessage.Type {\n" + " return $classname$.self\n" + "}\n", + "classname", + ClassName(descriptor_)); + + printer->Print("\n\n//Meta information declaration end\n\n"); + printer->Outdent(); + printer->Print("}\n\n"); + + GenerateBuilderSource(printer); } - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "size += extensionsSerializedSize()\n"); - } - - if (descriptor_->options().message_set_wire_format()) { - printer->Print( - "size += unknownFields.serializedSizeAsMessageSet()\n"); - } else { - printer->Print( - "size += unknownFields.serializedSize()\n"); - } - - printer->Print( - "memoizedSerializedSize = size\n" - "return size\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - void MessageGenerator::GenerateMessageDescriptionSource(io::Printer* printer) { - scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); - - vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); - } - sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "override public func writeDescriptionTo(inout output:String, indent:String) {\n"); - - printer->Indent(); - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size(); ) { - if (i == descriptor_->field_count()) { - GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]); + void MessageGenerator::GenerateMessageSerializationMethodsSource(io::Printer* printer) { + scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); + + vector sorted_extensions; + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeOrdering()); + + printer->Print( + "override public func writeToCodedOutputStream(output:CodedOutputStream) {\n"); + printer->Indent(); + // Merge the fields and the extension ranges, both sorted by field number. + for (int i = 0, j = 0; + i < descriptor_->field_count() || j < sorted_extensions.size(); ) { + if (i == descriptor_->field_count()) { + GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]); + } else if (j == sorted_extensions.size()) { + GenerateSerializeOneFieldSource(printer, sorted_fields[i++]); + } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { + GenerateSerializeOneFieldSource(printer, sorted_fields[i++]); + } else { + GenerateSerializeOneExtensionRangeSource(printer, sorted_extensions[j++]); + } + } + + if (descriptor_->options().message_set_wire_format()) { + printer->Print( + "unknownFields.writeAsMessageSetTo(output)\n"); } else { - GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]); + printer->Print( + "unknownFields.writeToCodedOutputStream(output)\n"); + } + printer->Outdent(); + + printer->Print("}\n"); + + printer->Print("override public func serializedSize() -> Int32 {\n"); + printer->Indent(); + printer->Print("var size:Int32 = memoizedSerializedSize\n" + "if size != -1 {\n" + " return size\n" + "}\n" + "\n" + "size = 0\n"); + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(sorted_fields[i]).GenerateSerializedSizeCodeSource(printer); + } + + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "size += extensionsSerializedSize()\n"); } + + if (descriptor_->options().message_set_wire_format()) { + printer->Print( + "size += unknownFields.serializedSizeAsMessageSet()\n"); + } else { + printer->Print( + "size += unknownFields.serializedSize()\n"); + } + + + printer->Print( + "memoizedSerializedSize = size\n" + "return size\n"); + printer->Outdent(); + printer->Print("}\n"); } - - printer->Print( - "unknownFields.writeDescriptionTo(&output, indent:indent)\n"); - - printer->Outdent(); - printer->Print( - "}\n"); - } - - - - - //TODO override equals - void MessageGenerator::GenerateMessageIsEqualSource(io::Printer* printer) { - scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); - - vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); + + void MessageGenerator::GenerateMessageDescriptionSource(io::Printer* printer) { + scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); + + vector sorted_extensions; + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeOrdering()); + + printer->Print( + "override public func writeDescriptionTo(inout output:String, indent:String) {\n"); + + printer->Indent(); + + // Merge the fields and the extension ranges, both sorted by field number. + for (int i = 0, j = 0; + i < descriptor_->field_count() || j < sorted_extensions.size(); ) { + if (i == descriptor_->field_count()) { + GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]); + } else if (j == sorted_extensions.size()) { + GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]); + } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { + GenerateDescriptionOneFieldSource(printer, sorted_fields[i++]); + } else { + GenerateDescriptionOneExtensionRangeSource(printer, sorted_extensions[j++]); + } + } + + printer->Print( + "unknownFields.writeDescriptionTo(&output, indent:indent)\n"); + + printer->Outdent(); + printer->Print( + "}\n"); } - sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "func == (lhs: $classname$, rhs: $classname$) -> Bool {\n","classname", ClassName(descriptor_)); - printer->Indent(); - printer->Print( - "if (lhs === rhs) {\n" - " return true\n" - "}\n" - ); - - - - - // Merge the fields and the extension ranges, both sorted by field number. - printer->Print("var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)\n"); - for (int i = 0, j = 0; i < descriptor_->field_count() || j < sorted_extensions.size(); ) { - - if (i == descriptor_->field_count()) - { - printer->Print("fieldCheck = fieldCheck && "); - GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]); - printer->Print("\n"); - } else if (j == sorted_extensions.size()) - { - printer->Print("fieldCheck = fieldCheck && "); - GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]); - printer->Print("\n"); - - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - printer->Print("fieldCheck = fieldCheck && "); - GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]); - printer->Print("\n"); - - } else { - printer->Print("fieldCheck = fieldCheck && "); - GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]); - printer->Print("\n"); + + + //TODO override equals + void MessageGenerator::GenerateMessageIsEqualSource(io::Printer* printer) { + scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); + + vector sorted_extensions; + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); } - + sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeOrdering()); + + printer->Print( + "func == (lhs: $classname$, rhs: $classname$) -> Bool {\n","classname", ClassName(descriptor_)); + printer->Indent(); + + + printer->Print( + "if (lhs === rhs) {\n" + " return true\n" + "}\n" + ); + + + + + // Merge the fields and the extension ranges, both sorted by field number. + printer->Print("var fieldCheck:Bool = (lhs.hashValue == rhs.hashValue)\n"); + for (int i = 0, j = 0; i < descriptor_->field_count() || j < sorted_extensions.size(); ) { + + if (i == descriptor_->field_count()) + { + printer->Print("fieldCheck = fieldCheck && "); + GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]); + printer->Print("\n"); + } else if (j == sorted_extensions.size()) + { + printer->Print("fieldCheck = fieldCheck && "); + GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]); + printer->Print("\n"); + + } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { + printer->Print("fieldCheck = fieldCheck && "); + GenerateIsEqualOneFieldSource(printer, sorted_fields[i++]); + printer->Print("\n"); + + } else { + printer->Print("fieldCheck = fieldCheck && "); + GenerateIsEqualOneExtensionRangeSource(printer, sorted_extensions[j++]); + printer->Print("\n"); + } + + } + + printer->Print("return (fieldCheck && (lhs.unknownFields == rhs.unknownFields))\n"); + + + printer->Outdent(); + printer->Print("}\n\n"); } - - printer->Print("return (fieldCheck && (lhs.unknownFields == rhs.unknownFields))\n"); - printer->Outdent(); - printer->Print("}\n\n"); - } - - - void MessageGenerator::GenerateMessageHashSource(io::Printer* printer) { - scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); - - vector sorted_extensions; - for (int i = 0; i < descriptor_->extension_range_count(); ++i) { - sorted_extensions.push_back(descriptor_->extension_range(i)); + void MessageGenerator::GenerateMessageHashSource(io::Printer* printer) { + scoped_array sorted_fields(SortFieldsByNumber(descriptor_)); + + vector sorted_extensions; + for (int i = 0; i < descriptor_->extension_range_count(); ++i) { + sorted_extensions.push_back(descriptor_->extension_range(i)); + } + sort(sorted_extensions.begin(), sorted_extensions.end(), + ExtensionRangeOrdering()); + + printer->Print( + "override public var hashValue:Int {\n"); + printer->Indent(); + printer->Indent(); + printer->Print("get {\n"); + + + printer->Indent(); + printer->Indent(); + printer->Print("var hashCode:Int = 7\n"); + + // // Merge the fields and the extension ranges, both sorted by field number. + for (int i = 0, j = 0; + i < descriptor_->field_count() || j < sorted_extensions.size(); ) { + if (i == descriptor_->field_count()) { + GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]); + } else if (j == sorted_extensions.size()) { + GenerateHashOneFieldSource(printer, sorted_fields[i++]); + } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { + GenerateHashOneFieldSource(printer, sorted_fields[i++]); + } else { + GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]); + } + } + + printer->Print("hashCode = (hashCode &* 31) &+ unknownFields.hashValue\n" + "return hashCode\n"); + + printer->Outdent(); + printer->Outdent(); + printer->Print("}\n"); + printer->Outdent(); + printer->Outdent(); + printer->Print( + "}\n"); + } - sort(sorted_extensions.begin(), sorted_extensions.end(), - ExtensionRangeOrdering()); - - printer->Print( - "override public var hashValue:Int {\n"); - printer->Indent(); - printer->Indent(); - printer->Print("get {\n"); - printer->Indent(); - printer->Indent(); - printer->Print("var hashCode:Int = 7\n"); - -// // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < descriptor_->field_count() || j < sorted_extensions.size(); ) { - if (i == descriptor_->field_count()) { - GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]); - } else if (j == sorted_extensions.size()) { - GenerateHashOneFieldSource(printer, sorted_fields[i++]); - } else if (sorted_fields[i]->number() < sorted_extensions[j]->start) { - GenerateHashOneFieldSource(printer, sorted_fields[i++]); - } else { - GenerateHashOneExtensionRangeSource(printer, sorted_extensions[j++]); - } + void MessageGenerator::GenerateParseFromMethodsSource(io::Printer* printer) { + printer->Print( + "class func parseFromData(data:[Byte]) -> $classname$ {\n" + " return $classname$.builder().mergeFromData(data).build()\n" + "}\n" + "class func parseFromData(data:[Byte], extensionRegistry:ExtensionRegistry) -> $classname$ {\n" + " return $classname$.builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()\n" + "}\n" + "class func parseFromInputStream(input:NSInputStream) -> $classname$ {\n" + " return $classname$.builder().mergeFromInputStream(input).build()\n" + "}\n" + "class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) ->$classname$ {\n" + " return $classname$.builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()\n" + "}\n" + "class func parseFromCodedInputStream(input:CodedInputStream) -> $classname$ {\n" + " return $classname$.builder().mergeFromCodedInputStream(input).build()\n" + "}\n" + "class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> $classname$ {\n" + " return $classname$.builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()\n" + "}\n", + "classname", ClassName(descriptor_)); } - - printer->Print("hashCode = (hashCode &* 31) &+ unknownFields.hashValue\n" - "return hashCode\n"); - - printer->Outdent(); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Outdent(); - printer->Print( - "}\n"); - - } - - - void MessageGenerator::GenerateParseFromMethodsSource(io::Printer* printer) { - printer->Print( - "class func parseFromData(data:[Byte]) -> $classname$ {\n" - " return $classname$.builder().mergeFromData(data).build()\n" - "}\n" - "class func parseFromData(data:[Byte], extensionRegistry:ExtensionRegistry) -> $classname$ {\n" - " return $classname$.builder().mergeFromData(data, extensionRegistry:extensionRegistry).build()\n" - "}\n" - "class func parseFromInputStream(input:NSInputStream) -> $classname$ {\n" - " return $classname$.builder().mergeFromInputStream(input).build()\n" - "}\n" - "class func parseFromInputStream(input:NSInputStream, extensionRegistry:ExtensionRegistry) ->$classname$ {\n" - " return $classname$.builder().mergeFromInputStream(input, extensionRegistry:extensionRegistry).build()\n" - "}\n" - "class func parseFromCodedInputStream(input:CodedInputStream) -> $classname$ {\n" - " return $classname$.builder().mergeFromCodedInputStream(input).build()\n" - "}\n" - "class func parseFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> $classname$ {\n" - " return $classname$.builder().mergeFromCodedInputStream(input, extensionRegistry:extensionRegistry).build()\n" - "}\n", - "classname", ClassName(descriptor_)); - } - - void MessageGenerator::GenerateParseFromExtensionMethodsSource(io::Printer* printer) { + + void MessageGenerator::GenerateParseFromExtensionMethodsSource(io::Printer* printer) { printer->Print( "extension $classname$ {\n" " class func parseFromNSData(data:NSData) -> $classname$ {\n" @@ -613,314 +613,314 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { " return $classname$.builder().mergeFromData(bytes, extensionRegistry:extensionRegistry).build()\n" " }\n" "}\n", - "classname", ClassName(descriptor_)); + "classname", ClassName(descriptor_)); } - - - void MessageGenerator::GenerateSerializeOneFieldSource( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateSerializationCodeSource(printer); - } - - - void MessageGenerator::GenerateSerializeOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "writeExtensionsToCodedOutputStream(output, startInclusive:Int32($from$), endExclusive:Int32($to$))\n", - "from", SimpleItoa(range->start), - "to", SimpleItoa(range->end)); - } - - void MessageGenerator::GenerateDescriptionOneFieldSource( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateDescriptionCodeSource(printer); - } - - - void MessageGenerator::GenerateDescriptionOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "writeExtensionDescription(&output, startInclusive:Int32($from$), endExclusive:Int32($to$), indent:indent)\n", - "from", SimpleItoa(range->start), - "to", SimpleItoa(range->end)); - } - - - void MessageGenerator::GenerateIsEqualOneFieldSource( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateIsEqualCodeSource(printer); - } - - - void MessageGenerator::GenerateIsEqualOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "lhs.isEqualExtensionsInOther(rhs, startInclusive:Int32($from$), endExclusive:Int32($to$))", - "from", SimpleItoa(range->start), "to", SimpleItoa(range->end)); - } - - - void MessageGenerator::GenerateHashOneFieldSource( - io::Printer* printer, const FieldDescriptor* field) { - field_generators_.get(field).GenerateHashCodeSource(printer); - } - - - void MessageGenerator::GenerateHashOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range) { - printer->Print( - "hashCode = (hashCode &* 31) &+ Int(hashExtensionsFrom(Int32($from$), endExclusive:Int32($to$)))\n", - "from", SimpleItoa(range->start), "to", SimpleItoa(range->end)); - } - - - void MessageGenerator::GenerateBuilderSource(io::Printer* printer) { - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "final class $classname$Builder : ExtendableMessageBuilder {\n", - "classname", ClassNameMessage(descriptor_)); - } else { - printer->Print( - "final class $classname$Builder : GeneratedMessageBuilder {\n", - "classname", ClassNameMessage(descriptor_)); - } - - printer->Indent(); - - printer->Print( - "private var builderResult:$classname$\n\n" - "required override init () {\n" - " builderResult = $classname$()\n" - " super.init()\n" - "}\n", - "classname", ClassName(descriptor_)); - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateBuilderMembersSource(printer); - } - - GenerateCommonBuilderMethodsSource(printer); - GenerateBuilderParsingMethodsSource(printer); - printer->Outdent(); - - - - printer->Print("}\n\n"); - } - - - void MessageGenerator::GenerateCommonBuilderMethodsSource(io::Printer* printer) { - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "override var internalGetResult:ExtendableMessage {\n" - " get {\n" - " return builderResult\n" - " }\n" - "}\n"); - } else { + + + void MessageGenerator::GenerateSerializeOneFieldSource( + io::Printer* printer, const FieldDescriptor* field) { + field_generators_.get(field).GenerateSerializationCodeSource(printer); + } + + + void MessageGenerator::GenerateSerializeOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range) { printer->Print( - "override var internalGetResult:GeneratedMessage {\n" - " get {\n" - " return builderResult\n" - " }\n" - "}\n"); + "writeExtensionsToCodedOutputStream(output, startInclusive:Int32($from$), endExclusive:Int32($to$))\n", + "from", SimpleItoa(range->start), + "to", SimpleItoa(range->end)); } - - printer->Print( - "override func clear() -> $classname$Builder {\n" - " builderResult = $classname$()\n" - " return self\n" - "}\n" - "override func clone() -> $classname$Builder {\n" - " return $classname$.builderWithPrototype(builderResult)\n" - "}\n", - "classname", ClassName(descriptor_)); - - printer->Print( - "override func build() -> $classname$ {\n" - " checkInitialized()\n" - " return buildPartial()\n" - "}\n" - "func buildPartial() -> $classname$ {\n", - "classname", ClassName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateBuildingCodeSource(printer); + void MessageGenerator::GenerateDescriptionOneFieldSource( + io::Printer* printer, const FieldDescriptor* field) { + field_generators_.get(field).GenerateDescriptionCodeSource(printer); } - - printer->Print( - " var returnMe:$classname$ = builderResult\n" - " return returnMe\n" - "}\n", - "classname", ClassName(descriptor_)); - - printer->Print("func mergeFrom(other:$classname$) -> $classname$Builder {\n","classname", ClassName(descriptor_)); - // Optimization: If other is the default instance, we know none of its - // fields are set so we can skip the merge. - printer->Indent(); - printer->Print("if (other == $classname$()) {\n" - " return self\n" - "}\n", - "classname", ClassName(descriptor_)); - - for (int i = 0; i < descriptor_->field_count(); i++) { - field_generators_.get(descriptor_->field(i)).GenerateMergingCodeSource(printer); + void MessageGenerator::GenerateDescriptionOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range) { + printer->Print( + "writeExtensionDescription(&output, startInclusive:Int32($from$), endExclusive:Int32($to$), indent:indent)\n", + "from", SimpleItoa(range->start), + "to", SimpleItoa(range->end)); } - - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "mergeExtensionFields(other)\n"); + + void MessageGenerator::GenerateIsEqualOneFieldSource( + io::Printer* printer, const FieldDescriptor* field) { + field_generators_.get(field).GenerateIsEqualCodeSource(printer); } - - printer->Print( - "mergeUnknownFields(other.unknownFields)\n" - "return self\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - ////////////////////////////////////////////////////////// - - void MessageGenerator::GenerateBuilderParsingMethodsSource(io::Printer* printer) { - scoped_array sorted_fields( - SortFieldsByNumber(descriptor_)); - - - printer->Print( - "override func mergeFromCodedInputStream(input:CodedInputStream) ->$classname$Builder {\n" - " return mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())\n" - "}\n" - "override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> $classname$Builder {\n", - "classname", ClassName(descriptor_)); - - printer->Indent(); - printer->Print( - "var unknownFieldsBuilder:UnknownFieldSetBuilder = UnknownFieldSet.builderWithUnknownFields(self.unknownFields)\n" - "while (true) {\n"); - printer->Indent(); - printer->Print( - "var tag = input.readTag()\n" - "switch tag {\n"); - - printer->Print( - "case 0: \n"); - printer->Indent(); - printer->Print( - "self.unknownFields = unknownFieldsBuilder.build()\n" - "return self\n" - "\n" - ); - printer->Outdent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = sorted_fields[i]; - uint32 tag = WireFormatLite::MakeTag(field->number(), - WireFormat::WireTypeForField(field)); - - printer->Print( - "case $tag$ :\n", - "tag", SimpleItoa(tag)); - - printer->Indent(); - field_generators_.get(field).GenerateParsingCodeSource(printer); - printer->Outdent(); - printer->Print("\n"); + + + void MessageGenerator::GenerateIsEqualOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range) { + printer->Print( + "lhs.isEqualExtensionsInOther(rhs, startInclusive:Int32($from$), endExclusive:Int32($to$))", + "from", SimpleItoa(range->start), "to", SimpleItoa(range->end)); } - printer->Print( - "default:\n" - " if (!parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag)) {\n" - " unknownFields = unknownFieldsBuilder.build()\n" - " return self\n" - " }\n" - "}\n"); - - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - - void MessageGenerator::GenerateIsInitializedSource(io::Printer* printer) { - printer->Print( - "override public func isInitialized() -> Bool {\n"); - printer->Indent(); - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (field->is_required()) { + void MessageGenerator::GenerateHashOneFieldSource( + io::Printer* printer, const FieldDescriptor* field) { + field_generators_.get(field).GenerateHashCodeSource(printer); + } + + + void MessageGenerator::GenerateHashOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range) { printer->Print( - "if !has$capitalized_name$ {\n" - " return false\n" - "}\n", - "capitalized_name", UnderscoresToCapitalizedCamelCase(field)); - } + "hashCode = (hashCode &* 31) &+ Int(hashExtensionsFrom(Int32($from$), endExclusive:Int32($to$)))\n", + "from", SimpleItoa(range->start), "to", SimpleItoa(range->end)); } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && - HasRequiredFields(field->message_type())) { - - map vars; - vars["type"] = ClassName(field->message_type()); - vars["name"] = UnderscoresToCamelCase(field); - vars["capitalized_name"] = UnderscoresToCapitalizedCamelCase(field); - - switch (field->label()) { - case FieldDescriptor::LABEL_REQUIRED: - printer->Print(vars, - "if !$name$.isInitialized() {\n" - " return false\n" - "}\n"); - break; - case FieldDescriptor::LABEL_OPTIONAL: - printer->Print(vars, - "if has$capitalized_name$ {\n" - " if !$name$.isInitialized() {\n" - " return false\n" - " }\n" - "}\n"); - break; - case FieldDescriptor::LABEL_REPEATED: - printer->Print(vars, - "var isInit$name$:Bool = true\n" - "for element in $name$ {\n" - " if (!element.isInitialized()) {\n" - " isInit$name$ = false\n" - " break \n" - " }\n" - "}\n" - "if !isInit$name$ {\n return isInit$name$\n }\n" - ); - break; - } - } + + + void MessageGenerator::GenerateBuilderSource(io::Printer* printer) { + + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "final class $classname$Builder : ExtendableMessageBuilder {\n", + "classname", ClassNameMessage(descriptor_)); + } else { + printer->Print( + "final class $classname$Builder : GeneratedMessageBuilder {\n", + "classname", ClassNameMessage(descriptor_)); + } + + printer->Indent(); + + printer->Print( + "private var builderResult:$classname$\n\n" + "required override init () {\n" + " builderResult = $classname$()\n" + " super.init()\n" + "}\n", + "classname", ClassName(descriptor_)); + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateBuilderMembersSource(printer); + } + + GenerateCommonBuilderMethodsSource(printer); + GenerateBuilderParsingMethodsSource(printer); + printer->Outdent(); + + + + printer->Print("}\n\n"); } - - if (descriptor_->extension_range_count() > 0) { - printer->Print( - "if !extensionsAreInitialized() {\n" - " return false\n" - "}\n"); + + + void MessageGenerator::GenerateCommonBuilderMethodsSource(io::Printer* printer) { + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "override var internalGetResult:ExtendableMessage {\n" + " get {\n" + " return builderResult\n" + " }\n" + "}\n"); + } else { + printer->Print( + "override var internalGetResult:GeneratedMessage {\n" + " get {\n" + " return builderResult\n" + " }\n" + "}\n"); + } + + printer->Print( + "override func clear() -> $classname$Builder {\n" + " builderResult = $classname$()\n" + " return self\n" + "}\n" + "override func clone() -> $classname$Builder {\n" + " return $classname$.builderWithPrototype(builderResult)\n" + "}\n", + "classname", ClassName(descriptor_)); + + printer->Print( + "override func build() -> $classname$ {\n" + " checkInitialized()\n" + " return buildPartial()\n" + "}\n" + "func buildPartial() -> $classname$ {\n", + "classname", ClassName(descriptor_)); + + + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateBuildingCodeSource(printer); + } + + + printer->Print( + " var returnMe:$classname$ = builderResult\n" + " return returnMe\n" + "}\n", + "classname", ClassName(descriptor_)); + + printer->Print("func mergeFrom(other:$classname$) -> $classname$Builder {\n","classname", ClassName(descriptor_)); + // Optimization: If other is the default instance, we know none of its + // fields are set so we can skip the merge. + printer->Indent(); + printer->Print("if (other == $classname$()) {\n" + " return self\n" + "}\n", + "classname", ClassName(descriptor_)); + + + for (int i = 0; i < descriptor_->field_count(); i++) { + field_generators_.get(descriptor_->field(i)).GenerateMergingCodeSource(printer); + } + + + + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "mergeExtensionFields(other)\n"); + } + + printer->Print( + "mergeUnknownFields(other.unknownFields)\n" + "return self\n"); + printer->Outdent(); + printer->Print("}\n"); + } + + ////////////////////////////////////////////////////////// + + void MessageGenerator::GenerateBuilderParsingMethodsSource(io::Printer* printer) { + scoped_array sorted_fields( + SortFieldsByNumber(descriptor_)); + + + printer->Print( + "override func mergeFromCodedInputStream(input:CodedInputStream) ->$classname$Builder {\n" + " return mergeFromCodedInputStream(input, extensionRegistry:ExtensionRegistry())\n" + "}\n" + "override func mergeFromCodedInputStream(input:CodedInputStream, extensionRegistry:ExtensionRegistry) -> $classname$Builder {\n", + "classname", ClassName(descriptor_)); + + printer->Indent(); + printer->Print( + "var unknownFieldsBuilder:UnknownFieldSetBuilder = UnknownFieldSet.builderWithUnknownFields(self.unknownFields)\n" + "while (true) {\n"); + printer->Indent(); + printer->Print( + "var tag = input.readTag()\n" + "switch tag {\n"); + + printer->Print( + "case 0: \n"); + printer->Indent(); + printer->Print( + "self.unknownFields = unknownFieldsBuilder.build()\n" + "return self\n" + "\n" + ); + printer->Outdent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = sorted_fields[i]; + uint32 tag = WireFormatLite::MakeTag(field->number(), + WireFormat::WireTypeForField(field)); + + printer->Print( + "case $tag$ :\n", + "tag", SimpleItoa(tag)); + + printer->Indent(); + field_generators_.get(field).GenerateParsingCodeSource(printer); + printer->Outdent(); + printer->Print("\n"); + } + printer->Print( + "default:\n" + " if (!parseUnknownField(input,unknownFields:unknownFieldsBuilder, extensionRegistry:extensionRegistry, tag:tag)) {\n" + " unknownFields = unknownFieldsBuilder.build()\n" + " return self\n" + " }\n" + "}\n"); + + + + printer->Outdent(); + printer->Print("}\n"); + printer->Outdent(); + printer->Print("}\n"); + } + + + void MessageGenerator::GenerateIsInitializedSource(io::Printer* printer) { + printer->Print( + "override public func isInitialized() -> Bool {\n"); + printer->Indent(); + // Check that all required fields in this message are set. + // TODO(kenton): We can optimize this when we switch to putting all the + // "has" fields into a single bitfield. + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = descriptor_->field(i); + + if (field->is_required()) { + printer->Print( + "if !has$capitalized_name$ {\n" + " return false\n" + "}\n", + "capitalized_name", UnderscoresToCapitalizedCamelCase(field)); + } + } + + // Now check that all embedded messages are initialized. + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* field = descriptor_->field(i); + if (field->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE && + HasRequiredFields(field->message_type())) { + + map vars; + vars["type"] = ClassName(field->message_type()); + vars["name"] = UnderscoresToCamelCase(field); + vars["capitalized_name"] = UnderscoresToCapitalizedCamelCase(field); + + switch (field->label()) { + case FieldDescriptor::LABEL_REQUIRED: + printer->Print(vars, + "if !$name$.isInitialized() {\n" + " return false\n" + "}\n"); + break; + case FieldDescriptor::LABEL_OPTIONAL: + printer->Print(vars, + "if has$capitalized_name$ {\n" + " if !$name$.isInitialized() {\n" + " return false\n" + " }\n" + "}\n"); + break; + case FieldDescriptor::LABEL_REPEATED: + printer->Print(vars, + "var isInit$name$:Bool = true\n" + "for element in $name$ {\n" + " if (!element.isInitialized()) {\n" + " isInit$name$ = false\n" + " break \n" + " }\n" + "}\n" + "if !isInit$name$ {\n return isInit$name$\n }\n" + ); + break; + } + } + } + + if (descriptor_->extension_range_count() > 0) { + printer->Print( + "if !extensionsAreInitialized() {\n" + " return false\n" + "}\n"); + } + + printer->Outdent(); + printer->Print( + " return true\n" + "}\n"); } - - printer->Outdent(); - printer->Print( - " return true\n" - "}\n"); - } } // namespace objectivec } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_message.h b/src/compiler/swift_message.h index 6f4020d..45a7519 100644 --- a/src/compiler/swift_message.h +++ b/src/compiler/swift_message.h @@ -25,69 +25,69 @@ #include "swift_field.h" namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class MessageGenerator { - public: - explicit MessageGenerator(const Descriptor* descriptor); - ~MessageGenerator(); - - void GenerateStaticVariablesInitialization(io::Printer* printer); - void GenerateStaticVariablesSource(io::Printer* printer); - void GenerateSource(io::Printer* printer); - void GenerateMessageIsEqualSource(io::Printer* printer); - void GenerateExtensionRegistrationSource(io::Printer* printer); - void DetermineDependencies(set* dependencies); - void GenerateParseFromExtensionMethodsSource(io::Printer* printer); - void GenerateGlobalStaticVariablesSource(io::Printer* printer, string rootclass); - private: - - void GenerateMessageSerializationMethodsSource(io::Printer* printer); - void GenerateParseFromMethodsSource(io::Printer* printer); - void GenerateSerializeOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - void GenerateSerializeOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateMessageDescriptionSource(io::Printer* printer); - void GenerateDescriptionOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - void GenerateDescriptionOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - - void GenerateIsEqualOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - void GenerateIsEqualOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateMessageHashSource(io::Printer* printer); - void GenerateHashOneFieldSource(io::Printer* printer, - const FieldDescriptor* field); - void GenerateHashOneExtensionRangeSource( - io::Printer* printer, const Descriptor::ExtensionRange* range); - - void GenerateBuilderSource(io::Printer* printer); - void GenerateCommonBuilderMethodsSource(io::Printer* printer); - void GenerateBuilderParsingMethodsSource(io::Printer* printer); - void GenerateIsInitializedSource(io::Printer* printer); - - const Descriptor* descriptor_; - FieldGeneratorMap field_generators_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class MessageGenerator { + public: + explicit MessageGenerator(const Descriptor* descriptor); + ~MessageGenerator(); + + void GenerateStaticVariablesInitialization(io::Printer* printer); + void GenerateStaticVariablesSource(io::Printer* printer); + void GenerateSource(io::Printer* printer); + void GenerateMessageIsEqualSource(io::Printer* printer); + void GenerateExtensionRegistrationSource(io::Printer* printer); + void DetermineDependencies(set* dependencies); + void GenerateParseFromExtensionMethodsSource(io::Printer* printer); + void GenerateGlobalStaticVariablesSource(io::Printer* printer, string rootclass); + private: + + void GenerateMessageSerializationMethodsSource(io::Printer* printer); + void GenerateParseFromMethodsSource(io::Printer* printer); + void GenerateSerializeOneFieldSource(io::Printer* printer, + const FieldDescriptor* field); + void GenerateSerializeOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range); + + void GenerateMessageDescriptionSource(io::Printer* printer); + void GenerateDescriptionOneFieldSource(io::Printer* printer, + const FieldDescriptor* field); + void GenerateDescriptionOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range); + + + void GenerateIsEqualOneFieldSource(io::Printer* printer, + const FieldDescriptor* field); + void GenerateIsEqualOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range); + + void GenerateMessageHashSource(io::Printer* printer); + void GenerateHashOneFieldSource(io::Printer* printer, + const FieldDescriptor* field); + void GenerateHashOneExtensionRangeSource( + io::Printer* printer, const Descriptor::ExtensionRange* range); + + void GenerateBuilderSource(io::Printer* printer); + void GenerateCommonBuilderMethodsSource(io::Printer* printer); + void GenerateBuilderParsingMethodsSource(io::Printer* printer); + void GenerateIsInitializedSource(io::Printer* printer); + + const Descriptor* descriptor_; + FieldGeneratorMap field_generators_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_MESSAGE_H diff --git a/src/compiler/swift_message_field.cc b/src/compiler/swift_message_field.cc index 911e5fe..16b60c2 100644 --- a/src/compiler/swift_message_field.cc +++ b/src/compiler/swift_message_field.cc @@ -27,334 +27,334 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - namespace { - void SetMessageVariables(const FieldDescriptor* descriptor, - map* variables) { - std::string name = UnderscoresToCamelCase(descriptor); - (*variables)["classname"] = ClassName(descriptor->containing_type()); - (*variables)["name"] = name; - (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["type"] = ClassName(descriptor->message_type()); - if (IsPrimitiveType(GetSwiftType(descriptor))) { - (*variables)["storage_type"] = ClassName(descriptor->message_type()); - (*variables)["storage_attribute"] = ""; - } else { - (*variables)["storage_type"] = string(ClassName(descriptor->message_type())); - (*variables)["storage_attribute"] = ""; + + namespace { + void SetMessageVariables(const FieldDescriptor* descriptor, + map* variables) { + std::string name = UnderscoresToCamelCase(descriptor); + (*variables)["classname"] = ClassName(descriptor->containing_type()); + (*variables)["name"] = name; + (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); + (*variables)["number"] = SimpleItoa(descriptor->number()); + (*variables)["type"] = ClassName(descriptor->message_type()); + if (IsPrimitiveType(GetSwiftType(descriptor))) { + (*variables)["storage_type"] = ClassName(descriptor->message_type()); + (*variables)["storage_attribute"] = ""; + } else { + (*variables)["storage_type"] = string(ClassName(descriptor->message_type())); + (*variables)["storage_attribute"] = ""; + } + (*variables)["group_or_message"] = + (descriptor->type() == FieldDescriptor::TYPE_GROUP) ? + "Group" : "Message"; + + if (isOneOfField(descriptor)) { + const OneofDescriptor* oneof = descriptor->containing_oneof(); + (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); + (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + } + } + } // namespace + + + MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor) + : descriptor_(descriptor) { + SetMessageVariables(descriptor, &variables_); + } + + + MessageFieldGenerator::~MessageFieldGenerator() { + } + + + + + + void MessageFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + // + // printer->Print(variables_,"@property (strong)$storage_attribute$ $storage_type$ $name$;\n"); + } + + + + void MessageFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + if (isOneOfField(descriptor_)) { + + printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" + " get {\n" + " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" + " return false\n" + " }\n" + " return true\n" + " }\n" + " set(newValue) {\n" + " }\n" + "}\n"); + + printer->Print(variables_,"private(set) var $name$:$type$!{\n" + " get {\n" + " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" + " }\n" + " set (newvalue) {\n" + " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" + " }\n" + "}\n"); + } + else { + printer->Print(variables_, "private(set) var has$capitalized_name$:Bool = false\n"); + printer->Print(variables_, "private(set) var $name$:$type$ = $type$()\n"); } - (*variables)["group_or_message"] = - (descriptor->type() == FieldDescriptor::TYPE_GROUP) ? - "Group" : "Message"; - if (isOneOfField(descriptor)) { - const OneofDescriptor* oneof = descriptor->containing_oneof(); - (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); - (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + } + + void MessageFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { + } + + void MessageFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + printer->Print(variables_, + "var has$capitalized_name$:Bool {\n" + " get {\n" + " return builderResult.has$capitalized_name$\n" + " }\n" + "}\n" + "var $name$:$storage_type$ {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (value) {\n" + " builderResult.has$capitalized_name$ = true\n" + " builderResult.$name$ = value\n" + " }\n" + "}\n" + "func set$capitalized_name$Builder(builderForValue:$type$Builder) -> $classname$Builder {\n" + " $name$ = builderForValue.build()\n" + " return self\n" + "}\n" + "func merge$capitalized_name$(value:$storage_type$) -> $classname$Builder {\n" + " if (builderResult.has$capitalized_name$ && builderResult.$name$ != $type$()) {\n" + " builderResult.$name$ = $type$.builderWithPrototype(builderResult.$name$).mergeFrom(value).buildPartial()\n" + " } else {\n" + " builderResult.$name$ = value\n" + " }\n" + " builderResult.has$capitalized_name$ = true\n" + " return self\n" + "}\n" + "func clear$capitalized_name$() -> $classname$Builder {\n" + " builderResult.has$capitalized_name$ = false\n" + " builderResult.$name$ = $type$()\n" + " return self\n" + "}\n"); + } + + void MessageFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if (other.has$capitalized_name$) {\n" + " merge$capitalized_name$(other.$name$)\n" + "}\n"); + } + + + + void MessageFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + void MessageFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "var subBuilder:$type$Builder = $type$.builder()\n" + "if has$capitalized_name$ {\n" + " subBuilder.mergeFrom($name$)\n" + "}\n"); + + if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { + printer->Print(variables_, + "input.readGroup($number$, builder:subBuilder, extensionRegistry:extensionRegistry)\n"); + } else { + printer->Print(variables_, + "input.readMessage(subBuilder, extensionRegistry:extensionRegistry)\n"); } + + printer->Print(variables_, + "$name$ = subBuilder.buildPartial()\n"); } - } // namespace - - - MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor) - : descriptor_(descriptor) { - SetMessageVariables(descriptor, &variables_); - } - - - MessageFieldGenerator::~MessageFieldGenerator() { - } - - - - - - void MessageFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { -// -// printer->Print(variables_,"@property (strong)$storage_attribute$ $storage_type$ $name$;\n"); - } - - - - void MessageFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { - if (isOneOfField(descriptor_)) { - - printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" - " get {\n" - " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" - " return false\n" - " }\n" - " return true\n" - " }\n" - " set(newValue) {\n" - " }\n" - "}\n"); - - printer->Print(variables_,"private(set) var $name$:$type$!{\n" - " get {\n" - " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" - " }\n" - " set (newvalue) {\n" - " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" - " }\n" - "}\n"); - } - else { - printer->Print(variables_, "private(set) var has$capitalized_name$:Bool = false\n"); - printer->Print(variables_, "private(set) var $name$:$type$ = $type$()\n"); - } - - } - - void MessageFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { - } - - void MessageFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - printer->Print(variables_, - "var has$capitalized_name$:Bool {\n" - " get {\n" - " return builderResult.has$capitalized_name$\n" - " }\n" - "}\n" - "var $name$:$storage_type$ {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (value) {\n" - " builderResult.has$capitalized_name$ = true\n" - " builderResult.$name$ = value\n" - " }\n" - "}\n" - "func set$capitalized_name$Builder(builderForValue:$type$Builder) -> $classname$Builder {\n" - " $name$ = builderForValue.build()\n" - " return self\n" - "}\n" - "func merge$capitalized_name$(value:$storage_type$) -> $classname$Builder {\n" - " if (builderResult.has$capitalized_name$ && builderResult.$name$ != $type$()) {\n" - " builderResult.$name$ = $type$.builderWithPrototype(builderResult.$name$).mergeFrom(value).buildPartial()\n" - " } else {\n" - " builderResult.$name$ = value\n" - " }\n" - " builderResult.has$capitalized_name$ = true\n" - " return self\n" - "}\n" - "func clear$capitalized_name$() -> $classname$Builder {\n" - " builderResult.has$capitalized_name$ = false\n" - " builderResult.$name$ = $type$()\n" - " return self\n" - "}\n"); - } - - void MessageFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if (other.has$capitalized_name$) {\n" - " merge$capitalized_name$(other.$name$)\n" - "}\n"); - } - - - - void MessageFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - void MessageFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "var subBuilder:$type$Builder = $type$.builder()\n" - "if has$capitalized_name$ {\n" - " subBuilder.mergeFrom($name$)\n" - "}\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "input.readGroup($number$, builder:subBuilder, extensionRegistry:extensionRegistry)\n"); - } else { - printer->Print(variables_, - "input.readMessage(subBuilder, extensionRegistry:extensionRegistry)\n"); + + + void MessageFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " output.write$group_or_message$($number$, value:$name$)\n" + "}\n"); } - - printer->Print(variables_, - "$name$ = subBuilder.buildPartial()\n"); - } - - - void MessageFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " output.write$group_or_message$($number$, value:$name$)\n" - "}\n"); - } - - - void MessageFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " size += WireFormat.compute$group_or_message$Size($number$, value:$name$)\n" - "}\n"); - } - - - void MessageFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " output += \"\\(indent) $name$ {\\n\"\n" - " $name$.writeDescriptionTo(&output, indent:\"\\(indent) \")\n" - " output += \"\\(indent) }\\n\"\n" - "}\n"); - } - - - void MessageFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); - } - - - void MessageFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " hashCode = (hashCode &* 31) &+ $name$.hashValue\n" - "}\n"); - } - - - void MessageFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - - } - - - string MessageFieldGenerator::GetBoxedType() const { - return ClassName(descriptor_->message_type()); - } - - - RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor) + + + void MessageFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " size += WireFormat.compute$group_or_message$Size($number$, value:$name$)\n" + "}\n"); + } + + + void MessageFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " output += \"\\(indent) $name$ {\\n\"\n" + " $name$.writeDescriptionTo(&output, indent:\"\\(indent) \")\n" + " output += \"\\(indent) }\\n\"\n" + "}\n"); + } + + + void MessageFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); + } + + + void MessageFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " hashCode = (hashCode &* 31) &+ $name$.hashValue\n" + "}\n"); + } + + + void MessageFieldGenerator::GenerateMembersSource(io::Printer* printer) const { + + } + + + string MessageFieldGenerator::GetBoxedType() const { + return ClassName(descriptor_->message_type()); + } + + + RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { - SetMessageVariables(descriptor, &variables_); - } - - - RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { - } - - void RepeatedMessageFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { -// if(isObjectArray(descriptor_)) -// { -// -// printer->Print(variables_, -// "@property (strong) NSMutableArray * $list_name$;\n"); -// -// } -// else -// { -// printer->Print(variables_, -// "@property (strong) PBAppendableArray * $list_name$;\n"); -// -// } - - } - - - void RepeatedMessageFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { - - } - - - void RepeatedMessageFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { -// printer->Print(variables_, "$name$ = [$storage_type$]()\n"); - } - - - - void RepeatedMessageFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - - printer->Print(variables_, "private(set) var $name$:Array<$storage_type$> = Array<$storage_type$>()\n"); - } - - - void RepeatedMessageFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - printer->Print(variables_, - "var $name$:Array<$storage_type$> {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (value) {\n" - " builderResult.$name$ = value\n" - " }\n" - "}\n" - "func clear$capitalized_name$() -> $classname$Builder {\n" - " builderResult.$name$.removeAll(keepCapacity: false)\n" - " return self\n" - "}\n"); - } - - void RepeatedMessageFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - - printer->Print(variables_, - "if !other.$name$.isEmpty {\n" - " builderResult.$name$ += other.$name$\n" - "}\n"); - } - - - void RepeatedMessageFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - void RepeatedMessageFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "var subBuilder = $type$.builder()\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print(variables_, - "input.readGroup($number$,builder:subBuilder,extensionRegistry:extensionRegistry)\n"); - } else { - printer->Print(variables_, - "input.readMessage(subBuilder,extensionRegistry:extensionRegistry)\n"); + SetMessageVariables(descriptor, &variables_); + } + + + RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { + } + + void RepeatedMessageFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + // if(isObjectArray(descriptor_)) + // { + // + // printer->Print(variables_, + // "@property (strong) NSMutableArray * $list_name$;\n"); + // + // } + // else + // { + // printer->Print(variables_, + // "@property (strong) PBAppendableArray * $list_name$;\n"); + // + // } + + } + + + void RepeatedMessageFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + + } + + + void RepeatedMessageFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { + // printer->Print(variables_, "$name$ = [$storage_type$]()\n"); + } + + + + void RepeatedMessageFieldGenerator::GenerateMembersSource(io::Printer* printer) const { + + printer->Print(variables_, "private(set) var $name$:Array<$storage_type$> = Array<$storage_type$>()\n"); + } + + + void RepeatedMessageFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + printer->Print(variables_, + "var $name$:Array<$storage_type$> {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (value) {\n" + " builderResult.$name$ = value\n" + " }\n" + "}\n" + "func clear$capitalized_name$() -> $classname$Builder {\n" + " builderResult.$name$.removeAll(keepCapacity: false)\n" + " return self\n" + "}\n"); + } + + void RepeatedMessageFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { + + printer->Print(variables_, + "if !other.$name$.isEmpty {\n" + " builderResult.$name$ += other.$name$\n" + "}\n"); + } + + + void RepeatedMessageFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + void RepeatedMessageFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "var subBuilder = $type$.builder()\n"); + + if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { + printer->Print(variables_, + "input.readGroup($number$,builder:subBuilder,extensionRegistry:extensionRegistry)\n"); + } else { + printer->Print(variables_, + "input.readMessage(subBuilder,extensionRegistry:extensionRegistry)\n"); + } + + printer->Print(variables_, + "$name$ += [subBuilder.buildPartial()]\n"); + } + + void RepeatedMessageFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "for element in $name$ {\n" + " output.write$group_or_message$($number$, value:element)\n" + "}\n"); + } + + void RepeatedMessageFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "for element in $name$ {\n" + " size += WireFormat.compute$group_or_message$Size($number$, value:element)\n" + "}\n"); + } + + void RepeatedMessageFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "var $name$ElementIndex:Int = 0\n" + "for element in $name$ {\n" + " output += \"\\(indent) $name$[\\($name$ElementIndex)] {\\n\"\n" + " element.writeDescriptionTo(&output, indent:\"\\(indent) \")\n" + " output += \"\\(indent)}\\n\"\n" + " $name$ElementIndex++\n" + "}\n"); + } + + void RepeatedMessageFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, "(lhs.$name$ == rhs.$name$)"); + } + + void RepeatedMessageFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "for element in $name$ {\n" + " hashCode = (hashCode &* 31) &+ element.hashValue\n" + "}\n"); + } + + string RepeatedMessageFieldGenerator::GetBoxedType() const { + return ClassName(descriptor_->message_type()); } - - printer->Print(variables_, - "$name$ += [subBuilder.buildPartial()]\n"); - } - - void RepeatedMessageFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "for element in $name$ {\n" - " output.write$group_or_message$($number$, value:element)\n" - "}\n"); - } - - void RepeatedMessageFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "for element in $name$ {\n" - " size += WireFormat.compute$group_or_message$Size($number$, value:element)\n" - "}\n"); - } - - void RepeatedMessageFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "var $name$ElementIndex:Int = 0\n" - "for element in $name$ {\n" - " output += \"\\(indent) $name$[\\($name$ElementIndex)] {\\n\"\n" - " element.writeDescriptionTo(&output, indent:\"\\(indent) \")\n" - " output += \"\\(indent)}\\n\"\n" - " $name$ElementIndex++\n" - "}\n"); - } - - void RepeatedMessageFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, "(lhs.$name$ == rhs.$name$)"); - } - - void RepeatedMessageFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "for element in $name$ {\n" - " hashCode = (hashCode &* 31) &+ element.hashValue\n" - "}\n"); - } - - string RepeatedMessageFieldGenerator::GetBoxedType() const { - return ClassName(descriptor_->message_type()); - } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_message_field.h b/src/compiler/swift_message_field.h index a8d75b5..352f8a7 100644 --- a/src/compiler/swift_message_field.h +++ b/src/compiler/swift_message_field.h @@ -24,68 +24,68 @@ #include "swift_field.h" namespace google { -namespace protobuf { -namespace compiler { -namespace swift { - -class MessageFieldGenerator : public FieldGenerator { - public: - explicit MessageFieldGenerator(const FieldDescriptor* descriptor); - ~MessageFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); -}; - -class RepeatedMessageFieldGenerator : public FieldGenerator { - public: - explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor); - ~RepeatedMessageFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - string GetBoxedType() const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace compiler { + namespace swift { + + class MessageFieldGenerator : public FieldGenerator { + public: + explicit MessageFieldGenerator(const FieldDescriptor* descriptor); + ~MessageFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + string GetBoxedType() const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(MessageFieldGenerator); + }; + + class RepeatedMessageFieldGenerator : public FieldGenerator { + public: + explicit RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor); + ~RepeatedMessageFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + string GetBoxedType() const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedMessageFieldGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_MESSAGE_FIELD_H diff --git a/src/compiler/swift_oneof.cc b/src/compiler/swift_oneof.cc index a9ab44d..efab1e5 100644 --- a/src/compiler/swift_oneof.cc +++ b/src/compiler/swift_oneof.cc @@ -27,10 +27,10 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - OneofGenerator::OneofGenerator(const OneofDescriptor* descriptor) + + OneofGenerator::OneofGenerator(const OneofDescriptor* descriptor) : descriptor_(descriptor) { - } + } const char* PrimitiveTypeName(const FieldDescriptor* field) { switch (field->type()) { @@ -57,106 +57,106 @@ namespace google { namespace protobuf { namespace compiler { namespace swift { GOOGLE_LOG(FATAL) << "Can't get here."; return NULL; } - - - OneofGenerator::~OneofGenerator() { - } - - - - - void OneofGenerator::GenerateSource(io::Printer* printer) { - printer->Print("\n\n//OneOf declaration start\n\n"); - - printer->Print("enum $classname$ {\n", - "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - - - printer->Indent(); - printer->Print("case $classname$OneOfNotSet\n\n", - "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - - printer->Print("func checkOneOfIsSet() -> Bool {\n" - " switch self {\n" - " case .$name$OneOfNotSet:\n" - " return false\n" - " default:\n" - " return true\n" - " }\n" - "}\n", - "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name()), - "name",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - printer->Outdent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - - const FieldDescriptor* fieldType = descriptor_->field(i); - printer->Indent(); - if (GetSwiftType(fieldType) == SWIFTTYPE_MESSAGE) { - - printer->Print("case $name$($type$)\n\n", - "name",UnderscoresToCapitalizedCamelCase(fieldType), - "type",ClassName(fieldType->message_type())); - - printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" - " switch value {\n" - " case .$name$(let enumValue):\n" - " return enumValue\n" - " default:\n" - " return nil\n" - " }\n" - "}\n", - "name",UnderscoresToCapitalizedCamelCase(fieldType), - "fieldType",ClassName(fieldType->message_type()), - "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - } - else if (GetSwiftType(fieldType) == SWIFTTYPE_ENUM) - { - const FieldDescriptor* enumDesc = descriptor_->field(i); - printer->Print("case $name$($type$)\n\n", - "name",UnderscoresToCapitalizedCamelCase(enumDesc->name()), - "type",ClassName(enumDesc->enum_type())); - - printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" - " switch value {\n" - " case .$name$(let enumValue):\n" - " return enumValue\n" - " default:\n" - " return nil\n" - " }\n" - "}\n", - "name",UnderscoresToCapitalizedCamelCase(enumDesc->name()), - "fieldType",ClassName(enumDesc->enum_type()), - "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - } - else - { - printer->Print("case $name$($type$)\n\n", - "name",UnderscoresToCapitalizedCamelCase(fieldType->name()), - "type",PrimitiveTypeName(fieldType)); - - printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" - " switch value {\n" - " case .$name$(let enumValue):\n" - " return enumValue\n" - " default:\n" - " return nil\n" - " }\n" - "}\n", - "name",UnderscoresToCapitalizedCamelCase(fieldType->name()), - "fieldType",PrimitiveTypeName(fieldType), - "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); - } - printer->Outdent(); - - } - - - printer->Print("}\n"); - - printer->Print("\n"); - printer->Print("\n\n//OneOf declaration end\n\n"); - - } + + + OneofGenerator::~OneofGenerator() { + } + + + + + void OneofGenerator::GenerateSource(io::Printer* printer) { + printer->Print("\n\n//OneOf declaration start\n\n"); + + printer->Print("enum $classname$ {\n", + "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + + + printer->Indent(); + printer->Print("case $classname$OneOfNotSet\n\n", + "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + + printer->Print("func checkOneOfIsSet() -> Bool {\n" + " switch self {\n" + " case .$name$OneOfNotSet:\n" + " return false\n" + " default:\n" + " return true\n" + " }\n" + "}\n", + "classname",UnderscoresToCapitalizedCamelCase(descriptor_->name()), + "name",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + printer->Outdent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + + const FieldDescriptor* fieldType = descriptor_->field(i); + printer->Indent(); + if (GetSwiftType(fieldType) == SWIFTTYPE_MESSAGE) { + + printer->Print("case $name$($type$)\n\n", + "name",UnderscoresToCapitalizedCamelCase(fieldType), + "type",ClassName(fieldType->message_type())); + + printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" + " switch value {\n" + " case .$name$(let enumValue):\n" + " return enumValue\n" + " default:\n" + " return nil\n" + " }\n" + "}\n", + "name",UnderscoresToCapitalizedCamelCase(fieldType), + "fieldType",ClassName(fieldType->message_type()), + "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + } + else if (GetSwiftType(fieldType) == SWIFTTYPE_ENUM) + { + const FieldDescriptor* enumDesc = descriptor_->field(i); + printer->Print("case $name$($type$)\n\n", + "name",UnderscoresToCapitalizedCamelCase(enumDesc->name()), + "type",ClassName(enumDesc->enum_type())); + + printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" + " switch value {\n" + " case .$name$(let enumValue):\n" + " return enumValue\n" + " default:\n" + " return nil\n" + " }\n" + "}\n", + "name",UnderscoresToCapitalizedCamelCase(enumDesc->name()), + "fieldType",ClassName(enumDesc->enum_type()), + "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + } + else + { + printer->Print("case $name$($type$)\n\n", + "name",UnderscoresToCapitalizedCamelCase(fieldType->name()), + "type",PrimitiveTypeName(fieldType)); + + printer->Print("static func get$name$(value:$type$) ->$fieldType$? {\n" + " switch value {\n" + " case .$name$(let enumValue):\n" + " return enumValue\n" + " default:\n" + " return nil\n" + " }\n" + "}\n", + "name",UnderscoresToCapitalizedCamelCase(fieldType->name()), + "fieldType",PrimitiveTypeName(fieldType), + "type",UnderscoresToCapitalizedCamelCase(descriptor_->name())); + } + printer->Outdent(); + + } + + + printer->Print("}\n"); + + printer->Print("\n"); + printer->Print("\n\n//OneOf declaration end\n\n"); + + } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_oneof.h b/src/compiler/swift_oneof.h index b928fab..813b8f3 100644 --- a/src/compiler/swift_oneof.h +++ b/src/compiler/swift_oneof.h @@ -24,32 +24,32 @@ #include namespace google { -namespace protobuf { - namespace io { - class Printer; // printer.h - } -} - -namespace protobuf { -namespace compiler { -namespace swift { - -class OneofGenerator { - public: - explicit OneofGenerator(const OneofDescriptor* descriptor); - ~OneofGenerator(); - - void GenerateSource(io::Printer* printer); - - private: - const OneofDescriptor* descriptor_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofGenerator); -}; - -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace io { + class Printer; // printer.h + } + } + + namespace protobuf { + namespace compiler { + namespace swift { + + class OneofGenerator { + public: + explicit OneofGenerator(const OneofDescriptor* descriptor); + ~OneofGenerator(); + + void GenerateSource(io::Printer* printer); + + private: + const OneofDescriptor* descriptor_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(OneofGenerator); + }; + + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // swift_ENUM_H diff --git a/src/compiler/swift_primitive_field.cc b/src/compiler/swift_primitive_field.cc index 8b5759f..072e75b 100644 --- a/src/compiler/swift_primitive_field.cc +++ b/src/compiler/swift_primitive_field.cc @@ -30,478 +30,478 @@ #include "swift_helpers.h" namespace google { namespace protobuf { namespace compiler { namespace swift { - - using internal::WireFormat; - using internal::WireFormatLite; - - namespace { - - const char* PrimitiveTypeName(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32 : return "Int32" ; - case FieldDescriptor::TYPE_UINT32 : return "UInt32"; - case FieldDescriptor::TYPE_SINT32 : return "Int32" ; - case FieldDescriptor::TYPE_FIXED32 : return "UInt32"; - case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; - - case FieldDescriptor::TYPE_INT64 : return "Int64" ; - case FieldDescriptor::TYPE_UINT64 : return "UInt64"; - case FieldDescriptor::TYPE_SINT64 : return "Int64" ; - case FieldDescriptor::TYPE_FIXED64 : return "UInt64"; - case FieldDescriptor::TYPE_SFIXED64: return "Int64" ; - - case FieldDescriptor::TYPE_FLOAT : return "Float" ; - case FieldDescriptor::TYPE_DOUBLE : return "Double" ; - case FieldDescriptor::TYPE_BOOL : return "Bool" ; - case FieldDescriptor::TYPE_STRING : return "String"; - case FieldDescriptor::TYPE_BYTES : return "Array" ; - default : return NULL; - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + + using internal::WireFormat; + using internal::WireFormatLite; + + namespace { + + const char* PrimitiveTypeName(const FieldDescriptor* field) { + switch (field->type()) { + case FieldDescriptor::TYPE_INT32 : return "Int32" ; + case FieldDescriptor::TYPE_UINT32 : return "UInt32"; + case FieldDescriptor::TYPE_SINT32 : return "Int32" ; + case FieldDescriptor::TYPE_FIXED32 : return "UInt32"; + case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; + + case FieldDescriptor::TYPE_INT64 : return "Int64" ; + case FieldDescriptor::TYPE_UINT64 : return "UInt64"; + case FieldDescriptor::TYPE_SINT64 : return "Int64" ; + case FieldDescriptor::TYPE_FIXED64 : return "UInt64"; + case FieldDescriptor::TYPE_SFIXED64: return "Int64" ; + + case FieldDescriptor::TYPE_FLOAT : return "Float" ; + case FieldDescriptor::TYPE_DOUBLE : return "Double" ; + case FieldDescriptor::TYPE_BOOL : return "Bool" ; + case FieldDescriptor::TYPE_STRING : return "String"; + case FieldDescriptor::TYPE_BYTES : return "Array" ; + default : return NULL; + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; + } + + + const char* GetCapitalizedArrayValueTypeName(const FieldDescriptor* field) { + switch (field->type()) { + case FieldDescriptor::TYPE_INT32 : return "Int32" ; + case FieldDescriptor::TYPE_UINT32 : return "Uint32"; + case FieldDescriptor::TYPE_SINT32 : return "Int32" ; + case FieldDescriptor::TYPE_FIXED32 : return "Uint32"; + case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; + case FieldDescriptor::TYPE_INT64 : return "Int64" ; + case FieldDescriptor::TYPE_UINT64 : return "Uint64"; + case FieldDescriptor::TYPE_SINT64 : return "Int64" ; + case FieldDescriptor::TYPE_FIXED64 : return "Uint64"; + case FieldDescriptor::TYPE_SFIXED64: return "Int64" ; + case FieldDescriptor::TYPE_FLOAT : return "Float" ; + case FieldDescriptor::TYPE_DOUBLE : return "Double"; + case FieldDescriptor::TYPE_BOOL : return "Bool" ; + case FieldDescriptor::TYPE_STRING : return "Object"; + case FieldDescriptor::TYPE_BYTES : return "Object"; + case FieldDescriptor::TYPE_ENUM : return "Object"; + case FieldDescriptor::TYPE_GROUP : return "Object"; + case FieldDescriptor::TYPE_MESSAGE : return "Object"; + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; + } + + const char* GetCapitalizedType(const FieldDescriptor* field) { + switch (field->type()) { + case FieldDescriptor::TYPE_INT32 : return "Int32" ; + case FieldDescriptor::TYPE_UINT32 : return "UInt32" ; + case FieldDescriptor::TYPE_SINT32 : return "SInt32" ; + case FieldDescriptor::TYPE_FIXED32 : return "Fixed32" ; + case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; + case FieldDescriptor::TYPE_INT64 : return "Int64" ; + case FieldDescriptor::TYPE_UINT64 : return "UInt64" ; + case FieldDescriptor::TYPE_SINT64 : return "SInt64" ; + case FieldDescriptor::TYPE_FIXED64 : return "Fixed64" ; + case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; + case FieldDescriptor::TYPE_FLOAT : return "Float" ; + case FieldDescriptor::TYPE_DOUBLE : return "Double" ; + case FieldDescriptor::TYPE_BOOL : return "Bool" ; + case FieldDescriptor::TYPE_STRING : return "String" ; + case FieldDescriptor::TYPE_BYTES : return "Data" ; + case FieldDescriptor::TYPE_ENUM : return "Enum" ; + case FieldDescriptor::TYPE_GROUP : return "Group" ; + case FieldDescriptor::TYPE_MESSAGE : return "Message" ; + } + + GOOGLE_LOG(FATAL) << "Can't get here."; + return NULL; + } + + // For encodings with fixed sizes, returns that size in bytes. Otherwise + // returns -1. + int FixedSize(FieldDescriptor::Type type) { + switch (type) { + case FieldDescriptor::TYPE_INT32 : return -1; + case FieldDescriptor::TYPE_INT64 : return -1; + case FieldDescriptor::TYPE_UINT32 : return -1; + case FieldDescriptor::TYPE_UINT64 : return -1; + case FieldDescriptor::TYPE_SINT32 : return -1; + case FieldDescriptor::TYPE_SINT64 : return -1; + case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; + case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; + case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; + case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; + case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; + case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; + + case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; + case FieldDescriptor::TYPE_ENUM : return -1; + + case FieldDescriptor::TYPE_STRING : return -1; + case FieldDescriptor::TYPE_BYTES : return -1; + case FieldDescriptor::TYPE_GROUP : return -1; + case FieldDescriptor::TYPE_MESSAGE : return -1; + + // No default because we want the compiler to complain if any new + // types are added. + } + GOOGLE_LOG(FATAL) << "Can't get here."; + return -1; + } + + void SetPrimitiveVariables(const FieldDescriptor* descriptor, map* variables) { + std::string name = UnderscoresToCamelCase(descriptor); + (*variables)["classname"] = ClassName(descriptor->containing_type()); + (*variables)["name"] = name; + (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); + (*variables)["number"] = SimpleItoa(descriptor->number()); + (*variables)["type"] = PrimitiveTypeName(descriptor); + + (*variables)["storage_type"] = PrimitiveTypeName(descriptor); + (*variables)["storage_attribute"] = ""; + if (isOneOfField(descriptor)) { + const OneofDescriptor* oneof = descriptor->containing_oneof(); + (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); + (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + } + + (*variables)["default"] = DefaultValue(descriptor); + (*variables)["capitalized_type"] = GetCapitalizedType(descriptor); + + (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor)); + (*variables)["tag_size"] = SimpleItoa( + WireFormat::TagSize(descriptor->number(), descriptor->type())); + + int fixed_size = FixedSize(descriptor->type()); + if (fixed_size != -1) { + (*variables)["fixed_size"] = SimpleItoa(fixed_size); + } + } + } // namespace + + + PrimitiveFieldGenerator::PrimitiveFieldGenerator(const FieldDescriptor* descriptor) + : descriptor_(descriptor) { + SetPrimitiveVariables(descriptor, &variables_); } - - - const char* GetCapitalizedArrayValueTypeName(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32 : return "Int32" ; - case FieldDescriptor::TYPE_UINT32 : return "Uint32"; - case FieldDescriptor::TYPE_SINT32 : return "Int32" ; - case FieldDescriptor::TYPE_FIXED32 : return "Uint32"; - case FieldDescriptor::TYPE_SFIXED32: return "Int32" ; - case FieldDescriptor::TYPE_INT64 : return "Int64" ; - case FieldDescriptor::TYPE_UINT64 : return "Uint64"; - case FieldDescriptor::TYPE_SINT64 : return "Int64" ; - case FieldDescriptor::TYPE_FIXED64 : return "Uint64"; - case FieldDescriptor::TYPE_SFIXED64: return "Int64" ; - case FieldDescriptor::TYPE_FLOAT : return "Float" ; - case FieldDescriptor::TYPE_DOUBLE : return "Double"; - case FieldDescriptor::TYPE_BOOL : return "Bool" ; - case FieldDescriptor::TYPE_STRING : return "Object"; - case FieldDescriptor::TYPE_BYTES : return "Object"; - case FieldDescriptor::TYPE_ENUM : return "Object"; - case FieldDescriptor::TYPE_GROUP : return "Object"; - case FieldDescriptor::TYPE_MESSAGE : return "Object"; - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + + + + PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { } - - const char* GetCapitalizedType(const FieldDescriptor* field) { - switch (field->type()) { - case FieldDescriptor::TYPE_INT32 : return "Int32" ; - case FieldDescriptor::TYPE_UINT32 : return "UInt32" ; - case FieldDescriptor::TYPE_SINT32 : return "SInt32" ; - case FieldDescriptor::TYPE_FIXED32 : return "Fixed32" ; - case FieldDescriptor::TYPE_SFIXED32: return "SFixed32"; - case FieldDescriptor::TYPE_INT64 : return "Int64" ; - case FieldDescriptor::TYPE_UINT64 : return "UInt64" ; - case FieldDescriptor::TYPE_SINT64 : return "SInt64" ; - case FieldDescriptor::TYPE_FIXED64 : return "Fixed64" ; - case FieldDescriptor::TYPE_SFIXED64: return "SFixed64"; - case FieldDescriptor::TYPE_FLOAT : return "Float" ; - case FieldDescriptor::TYPE_DOUBLE : return "Double" ; - case FieldDescriptor::TYPE_BOOL : return "Bool" ; - case FieldDescriptor::TYPE_STRING : return "String" ; - case FieldDescriptor::TYPE_BYTES : return "Data" ; - case FieldDescriptor::TYPE_ENUM : return "Enum" ; - case FieldDescriptor::TYPE_GROUP : return "Group" ; - case FieldDescriptor::TYPE_MESSAGE : return "Message" ; - } - - GOOGLE_LOG(FATAL) << "Can't get here."; - return NULL; + void PrimitiveFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + // if (IsReferenceType(GetSwiftType(descriptor_))) { + // printer->Print(variables_,"@property (strong)$storage_attribute$ $storage_type$ $name$;\n"); + // + // } else { + // printer->Print(variables_, + // "@property $storage_type$ $name$;\n"); + // } } - - // For encodings with fixed sizes, returns that size in bytes. Otherwise - // returns -1. - int FixedSize(FieldDescriptor::Type type) { - switch (type) { - case FieldDescriptor::TYPE_INT32 : return -1; - case FieldDescriptor::TYPE_INT64 : return -1; - case FieldDescriptor::TYPE_UINT32 : return -1; - case FieldDescriptor::TYPE_UINT64 : return -1; - case FieldDescriptor::TYPE_SINT32 : return -1; - case FieldDescriptor::TYPE_SINT64 : return -1; - case FieldDescriptor::TYPE_FIXED32 : return WireFormatLite::kFixed32Size; - case FieldDescriptor::TYPE_FIXED64 : return WireFormatLite::kFixed64Size; - case FieldDescriptor::TYPE_SFIXED32: return WireFormatLite::kSFixed32Size; - case FieldDescriptor::TYPE_SFIXED64: return WireFormatLite::kSFixed64Size; - case FieldDescriptor::TYPE_FLOAT : return WireFormatLite::kFloatSize; - case FieldDescriptor::TYPE_DOUBLE : return WireFormatLite::kDoubleSize; - - case FieldDescriptor::TYPE_BOOL : return WireFormatLite::kBoolSize; - case FieldDescriptor::TYPE_ENUM : return -1; - - case FieldDescriptor::TYPE_STRING : return -1; - case FieldDescriptor::TYPE_BYTES : return -1; - case FieldDescriptor::TYPE_GROUP : return -1; - case FieldDescriptor::TYPE_MESSAGE : return -1; - - // No default because we want the compiler to complain if any new - // types are added. - } - GOOGLE_LOG(FATAL) << "Can't get here."; - return -1; + + + void PrimitiveFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + + if (isOneOfField(descriptor_)) { + printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" + " get {\n" + " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" + " return false\n" + " }\n" + " return true\n" + " }\n" + " set(newValue) {\n" + " }\n" + "}\n"); + + printer->Print(variables_,"private(set) var $name$:$storage_type$!{\n" + " get {\n" + " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" + " }\n" + " set (newvalue) {\n" + " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" + " }\n" + "}\n"); + } + else + { + printer->Print(variables_,"private(set) var has$capitalized_name$:Bool = false\n"); + printer->Print(variables_,"private(set) var $name$:$storage_type$ = $default$\n\n"); + } } - - void SetPrimitiveVariables(const FieldDescriptor* descriptor, map* variables) { - std::string name = UnderscoresToCamelCase(descriptor); - (*variables)["classname"] = ClassName(descriptor->containing_type()); - (*variables)["name"] = name; - (*variables)["capitalized_name"] = UnderscoresToCapitalizedCamelCase(descriptor); - (*variables)["number"] = SimpleItoa(descriptor->number()); - (*variables)["type"] = PrimitiveTypeName(descriptor); - - (*variables)["storage_type"] = PrimitiveTypeName(descriptor); - (*variables)["storage_attribute"] = ""; - if (isOneOfField(descriptor)) { - const OneofDescriptor* oneof = descriptor->containing_oneof(); - (*variables)["oneof_name"] = UnderscoresToCapitalizedCamelCase(oneof->name()); - (*variables)["oneof_class_name"] = ClassNameOneof(oneof); + + + + void PrimitiveFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { + } + + + void PrimitiveFieldGenerator::GenerateMembersSource(io::Printer* printer) const { + } + + void PrimitiveFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + + printer->Print(variables_, + "var has$capitalized_name$:Bool {\n" + " get {\n" + " return builderResult.has$capitalized_name$\n" + " }\n" + "}\n" + "var $name$:$storage_type$ {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (value) {\n" + " builderResult.has$capitalized_name$ = true\n" + " builderResult.$name$ = value\n" + " }\n" + "}\n" + "func clear$capitalized_name$() -> $classname$Builder{\n" + " builderResult.has$capitalized_name$ = false\n" + " builderResult.$name$ = $default$\n" + " return self\n" + "}\n"); + + } + + + void PrimitiveFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if other.has$capitalized_name$ {\n" + " $name$ = other.$name$\n" + "}\n"); + } + + void PrimitiveFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + void PrimitiveFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "$name$ = input.read$capitalized_type$()\n"); + } + + void PrimitiveFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " output.write$capitalized_type$($number$, value:$name$)\n" + "}\n"); + } + + void PrimitiveFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " size += WireFormat.compute$capitalized_type$Size($number$, value:$name$)\n" + "}\n"); + } + + void PrimitiveFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " output += \"\\(indent) $name$: \\($name$) \\n\"\n"); + printer->Print(variables_, + "}\n"); + } + + void PrimitiveFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); + + } + + void PrimitiveFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + if (descriptor_->type() == FieldDescriptor::TYPE_BYTES) { + printer->Print(variables_, + "for value in $name$ {\n" + " hashCode = (hashCode &* 31) &+ value.hashValue\n" + "}\n"); } - - (*variables)["default"] = DefaultValue(descriptor); - (*variables)["capitalized_type"] = GetCapitalizedType(descriptor); - - (*variables)["tag"] = SimpleItoa(WireFormat::MakeTag(descriptor)); - (*variables)["tag_size"] = SimpleItoa( - WireFormat::TagSize(descriptor->number(), descriptor->type())); - - int fixed_size = FixedSize(descriptor->type()); - if (fixed_size != -1) { - (*variables)["fixed_size"] = SimpleItoa(fixed_size); + else + { + printer->Print(variables_, + "if has$capitalized_name$ {\n" + " hashCode = (hashCode &* 31) &+ $name$.hashValue\n" + "}\n"); } + } - } // namespace - - - PrimitiveFieldGenerator::PrimitiveFieldGenerator(const FieldDescriptor* descriptor) - : descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, &variables_); - } - - - PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { - } - void PrimitiveFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { -// if (IsReferenceType(GetSwiftType(descriptor_))) { -// printer->Print(variables_,"@property (strong)$storage_attribute$ $storage_type$ $name$;\n"); -// -// } else { -// printer->Print(variables_, -// "@property $storage_type$ $name$;\n"); -// } - } - - - void PrimitiveFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { - - if (isOneOfField(descriptor_)) { - printer->Print(variables_,"private(set) var has$capitalized_name$:Bool {\n" - " get {\n" - " if $oneof_class_name$.get$capitalized_name$(storage$oneof_name$) == nil {\n" - " return false\n" - " }\n" - " return true\n" - " }\n" - " set(newValue) {\n" - " }\n" - "}\n"); - - printer->Print(variables_,"private(set) var $name$:$storage_type$!{\n" - " get {\n" - " return $oneof_class_name$.get$capitalized_name$(storage$oneof_name$)\n" - " }\n" - " set (newvalue) {\n" - " storage$oneof_name$ = $oneof_class_name$.$capitalized_name$(newvalue)\n" - " }\n" - "}\n"); - } - else - { - printer->Print(variables_,"private(set) var has$capitalized_name$:Bool = false\n"); - printer->Print(variables_,"private(set) var $name$:$storage_type$ = $default$\n\n"); - } - } - - - - void PrimitiveFieldGenerator::GenerateInitializationSource(io::Printer* printer) const { - } - - - void PrimitiveFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - } - - void PrimitiveFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - - printer->Print(variables_, - "var has$capitalized_name$:Bool {\n" - " get {\n" - " return builderResult.has$capitalized_name$\n" - " }\n" - "}\n" - "var $name$:$storage_type$ {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (value) {\n" - " builderResult.has$capitalized_name$ = true\n" - " builderResult.$name$ = value\n" - " }\n" - "}\n" - "func clear$capitalized_name$() -> $classname$Builder{\n" - " builderResult.has$capitalized_name$ = false\n" - " builderResult.$name$ = $default$\n" - " return self\n" - "}\n"); - - } - - - void PrimitiveFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if other.has$capitalized_name$ {\n" - " $name$ = other.$name$\n" - "}\n"); - } - - void PrimitiveFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - void PrimitiveFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "$name$ = input.read$capitalized_type$()\n"); - } - - void PrimitiveFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " output.write$capitalized_type$($number$, value:$name$)\n" - "}\n"); - } - - void PrimitiveFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " size += WireFormat.compute$capitalized_type$Size($number$, value:$name$)\n" - "}\n"); - } - - void PrimitiveFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " output += \"\\(indent) $name$: \\($name$) \\n\"\n"); - printer->Print(variables_, - "}\n"); - } - - void PrimitiveFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "(lhs.has$capitalized_name$ == rhs.has$capitalized_name$) && (!lhs.has$capitalized_name$ || lhs.$name$ == rhs.$name$)"); - - } - - void PrimitiveFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - if (descriptor_->type() == FieldDescriptor::TYPE_BYTES) { - printer->Print(variables_, - "for value in $name$ {\n" - " hashCode = (hashCode &* 31) &+ value.hashValue\n" - "}\n"); - } - else - { - printer->Print(variables_, - "if has$capitalized_name$ {\n" - " hashCode = (hashCode &* 31) &+ $name$.hashValue\n" - "}\n"); - } - - } - - RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor) + RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor) : descriptor_(descriptor) { - SetPrimitiveVariables(descriptor, &variables_); - } - - - RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { - } - - void RepeatedPrimitiveFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { -// if(isObjectArray(descriptor_)) -// { -// printer->Print(variables_, "@property (strong) NSMutableArray * $list_name$;\n"); -// } -// else -// { -// printer->Print(variables_, "@property (strong) PBAppendableArray * $list_name$;\n"); -// } - - } - - - void RepeatedPrimitiveFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { -// printer->Print(variables_, "var $name$:[$storage_type$]\n"); - } - - - void RepeatedPrimitiveFieldGenerator::GenerateInitializationSource(io::Printer* printer) const {; - } - - void RepeatedPrimitiveFieldGenerator::GenerateMembersSource(io::Printer* printer) const { - - printer->Print(variables_, "private(set) var $name$:Array<$storage_type$> = Array<$storage_type$>()\n"); - if (descriptor_->options().packed()) { - printer->Print(variables_,"private var $name$MemoizedSerializedSize:Int32 = -1\n"); - } - } - - void RepeatedPrimitiveFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { - - - printer->Print(variables_, - "var $name$:Array<$storage_type$> {\n" - " get {\n" - " return builderResult.$name$\n" - " }\n" - " set (array) {\n" - " builderResult.$name$ = array\n" - " }\n" - "}\n" - "func clear$capitalized_name$() -> $classname$Builder {\n" - " builderResult.$name$.removeAll(keepCapacity: false)\n" - " return self\n" - "}\n"); - } - - void RepeatedPrimitiveFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "if !other.$name$.isEmpty {\n" - " builderResult.$name$ += other.$name$\n" - "}\n"); - } - - - void RepeatedPrimitiveFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { - } - - - void RepeatedPrimitiveFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { - if (descriptor_->options().packed()) - { - printer->Print(variables_, - "var length:Int32 = input.readRawVarint32()\n" - "var limit:Int32 = input.pushLimit(length)\n" - "while (input.bytesUntilLimit() > 0) {\n" - " builderResult.$name$ += [input.read$capitalized_type$()]\n" - "}\n" - "input.popLimit(limit)\n"); - } - else - { - printer->Print(variables_, - "$name$ += [input.read$capitalized_type$()]\n"); - } -} - - - void RepeatedPrimitiveFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { - - printer->Print(variables_,"if !$name$.isEmpty {\n"); - printer->Indent(); - - if (descriptor_->options().packed()) { + SetPrimitiveVariables(descriptor, &variables_); + } + + + RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { + } + + void RepeatedPrimitiveFieldGenerator::GenerateExtensionSource(io::Printer* printer) const { + // if(isObjectArray(descriptor_)) + // { + // printer->Print(variables_, "@property (strong) NSMutableArray * $list_name$;\n"); + // } + // else + // { + // printer->Print(variables_, "@property (strong) PBAppendableArray * $list_name$;\n"); + // } + + } + + + void RepeatedPrimitiveFieldGenerator::GenerateSynthesizeSource(io::Printer* printer) const { + // printer->Print(variables_, "var $name$:[$storage_type$]\n"); + } + + + void RepeatedPrimitiveFieldGenerator::GenerateInitializationSource(io::Printer* printer) const {; + } + + void RepeatedPrimitiveFieldGenerator::GenerateMembersSource(io::Printer* printer) const { + + printer->Print(variables_, "private(set) var $name$:Array<$storage_type$> = Array<$storage_type$>()\n"); + if (descriptor_->options().packed()) { + printer->Print(variables_,"private var $name$MemoizedSerializedSize:Int32 = -1\n"); + } + } + + void RepeatedPrimitiveFieldGenerator::GenerateBuilderMembersSource(io::Printer* printer) const { + + printer->Print(variables_, - "output.writeRawVarint32($tag$)\n" - "output.writeRawVarint32($name$MemoizedSerializedSize)\n" - "for value in $name$ {\n" - " output.write$capitalized_type$NoTag(value)\n" - "}\n"); - } else { + "var $name$:Array<$storage_type$> {\n" + " get {\n" + " return builderResult.$name$\n" + " }\n" + " set (array) {\n" + " builderResult.$name$ = array\n" + " }\n" + "}\n" + "func clear$capitalized_name$() -> $classname$Builder {\n" + " builderResult.$name$.removeAll(keepCapacity: false)\n" + " return self\n" + "}\n"); + } + + void RepeatedPrimitiveFieldGenerator::GenerateMergingCodeSource(io::Printer* printer) const { printer->Print(variables_, - "for value in $name$ {\n" - " output.write$capitalized_type$($number$, value:value)\n" - "}\n"); - } - printer->Outdent(); - printer->Print("}\n"); - } - - - void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + "if !other.$name$.isEmpty {\n" + " builderResult.$name$ += other.$name$\n" + "}\n"); + } - printer->Print(variables_, - "var dataSize$capitalized_name$:Int32 = 0\n"); - - if (FixedSize(descriptor_->type()) == -1) { - printer->Print(variables_, - "for element in $name$ {\n" - " dataSize$capitalized_name$ += WireFormat.compute$capitalized_type$SizeNoTag(element)\n" - "}\n"); - } else { + + void RepeatedPrimitiveFieldGenerator::GenerateBuildingCodeSource(io::Printer* printer) const { + } + + + void RepeatedPrimitiveFieldGenerator::GenerateParsingCodeSource(io::Printer* printer) const { + if (descriptor_->options().packed()) + { + printer->Print(variables_, + "var length:Int32 = input.readRawVarint32()\n" + "var limit:Int32 = input.pushLimit(length)\n" + "while (input.bytesUntilLimit() > 0) {\n" + " builderResult.$name$ += [input.read$capitalized_type$()]\n" + "}\n" + "input.popLimit(limit)\n"); + } + else + { + printer->Print(variables_, + "$name$ += [input.read$capitalized_type$()]\n"); + } + } + + + void RepeatedPrimitiveFieldGenerator::GenerateSerializationCodeSource(io::Printer* printer) const { + + printer->Print(variables_,"if !$name$.isEmpty {\n"); + printer->Indent(); + + if (descriptor_->options().packed()) { + printer->Print(variables_, + "output.writeRawVarint32($tag$)\n" + "output.writeRawVarint32($name$MemoizedSerializedSize)\n" + "for value in $name$ {\n" + " output.write$capitalized_type$NoTag(value)\n" + "}\n"); + } else { + printer->Print(variables_, + "for value in $name$ {\n" + " output.write$capitalized_type$($number$, value:value)\n" + "}\n"); + } + printer->Outdent(); + printer->Print("}\n"); + } + + + void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCodeSource(io::Printer* printer) const { + printer->Print(variables_, - "dataSize$capitalized_name$ = $fixed_size$ * Int32($name$.count)\n"); - } - - printer->Print(variables_,"size += dataSize$capitalized_name$\n"); - - if (descriptor_->options().packed()) { - printer->Print(variables_, - "if !$name$.isEmpty {\n" - " size += $tag_size$\n" - " size += WireFormat.computeInt32SizeNoTag(dataSize$capitalized_name$)\n" - "}\n" - "$name$MemoizedSerializedSize = dataSize$capitalized_name$\n"); - } else { - printer->Print(variables_, - "size += $tag_size$ * Int32($name$.count)\n"); + "var dataSize$capitalized_name$:Int32 = 0\n"); + + if (FixedSize(descriptor_->type()) == -1) { + printer->Print(variables_, + "for element in $name$ {\n" + " dataSize$capitalized_name$ += WireFormat.compute$capitalized_type$SizeNoTag(element)\n" + "}\n"); + } else { + printer->Print(variables_, + "dataSize$capitalized_name$ = $fixed_size$ * Int32($name$.count)\n"); + } + + printer->Print(variables_,"size += dataSize$capitalized_name$\n"); + + if (descriptor_->options().packed()) { + printer->Print(variables_, + "if !$name$.isEmpty {\n" + " size += $tag_size$\n" + " size += WireFormat.computeInt32SizeNoTag(dataSize$capitalized_name$)\n" + "}\n" + "$name$MemoizedSerializedSize = dataSize$capitalized_name$\n"); + } else { + printer->Print(variables_, + "size += $tag_size$ * Int32($name$.count)\n"); + } + + } - - } - - - void RepeatedPrimitiveFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { - + + void RepeatedPrimitiveFieldGenerator::GenerateDescriptionCodeSource(io::Printer* printer) const { + printer->Print(variables_, - "var $name$ElementIndex:Int = 0\n" - "for element in $name$ {\n" - " output += \"\\(indent) $name$[\\($name$ElementIndex)]: \\(element)\\n\"\n" - " $name$ElementIndex++\n" - "}\n"); - } - - - void RepeatedPrimitiveFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { - printer->Print(variables_, - "(lhs.$name$ == rhs.$name$)"); - } - - - void RepeatedPrimitiveFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { - - if (descriptor_->type() == FieldDescriptor::TYPE_BYTES) { - printer->Print(variables_, - "for value in $name$ {\n" - " for element in value {\n" - " hashCode = (hashCode &* 31) &+ element.hashValue\n" - " }\n" - "}\n"); - } - else - { - printer->Print(variables_, - "for element in $name$ {\n" - " hashCode = (hashCode &* 31) &+ element.hashValue\n" - "}\n"); - } - - } + "var $name$ElementIndex:Int = 0\n" + "for element in $name$ {\n" + " output += \"\\(indent) $name$[\\($name$ElementIndex)]: \\(element)\\n\"\n" + " $name$ElementIndex++\n" + "}\n"); + } + + + void RepeatedPrimitiveFieldGenerator::GenerateIsEqualCodeSource(io::Printer* printer) const { + printer->Print(variables_, + "(lhs.$name$ == rhs.$name$)"); + } + + + void RepeatedPrimitiveFieldGenerator::GenerateHashCodeSource(io::Printer* printer) const { + + if (descriptor_->type() == FieldDescriptor::TYPE_BYTES) { + printer->Print(variables_, + "for value in $name$ {\n" + " for element in value {\n" + " hashCode = (hashCode &* 31) &+ element.hashValue\n" + " }\n" + "}\n"); + } + else + { + printer->Print(variables_, + "for element in $name$ {\n" + " hashCode = (hashCode &* 31) &+ element.hashValue\n" + "}\n"); + } + + } } // namespace swift } // namespace compiler } // namespace protobuf diff --git a/src/compiler/swift_primitive_field.h b/src/compiler/swift_primitive_field.h index 4d2c80c..6eb7119 100644 --- a/src/compiler/swift_primitive_field.h +++ b/src/compiler/swift_primitive_field.h @@ -24,64 +24,64 @@ #include "swift_field.h" namespace google { -namespace protobuf { -namespace compiler { -namespace swift { - -class PrimitiveFieldGenerator : public FieldGenerator { - public: - explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor); - ~PrimitiveFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); -}; - -class RepeatedPrimitiveFieldGenerator : public FieldGenerator { - public: - explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor); - ~RepeatedPrimitiveFieldGenerator(); - - void GenerateExtensionSource(io::Printer* printer) const; - void GenerateSynthesizeSource(io::Printer* printer) const; - void GenerateInitializationSource(io::Printer* printer) const; - void GenerateMembersSource(io::Printer* printer) const; - void GenerateBuilderMembersSource(io::Printer* printer) const; - void GenerateMergingCodeSource(io::Printer* printer) const; - void GenerateBuildingCodeSource(io::Printer* printer) const; - void GenerateParsingCodeSource(io::Printer* printer) const; - void GenerateSerializationCodeSource(io::Printer* printer) const; - void GenerateSerializedSizeCodeSource(io::Printer* printer) const; - void GenerateDescriptionCodeSource(io::Printer* printer) const; - void GenerateIsEqualCodeSource(io::Printer* printer) const; - void GenerateHashCodeSource(io::Printer* printer) const; - - private: - const FieldDescriptor* descriptor_; - map variables_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); -}; -} // namespace swift -} // namespace compiler -} // namespace protobuf + namespace protobuf { + namespace compiler { + namespace swift { + + class PrimitiveFieldGenerator : public FieldGenerator { + public: + explicit PrimitiveFieldGenerator(const FieldDescriptor* descriptor); + ~PrimitiveFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); + }; + + class RepeatedPrimitiveFieldGenerator : public FieldGenerator { + public: + explicit RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor); + ~RepeatedPrimitiveFieldGenerator(); + + void GenerateExtensionSource(io::Printer* printer) const; + void GenerateSynthesizeSource(io::Printer* printer) const; + void GenerateInitializationSource(io::Printer* printer) const; + void GenerateMembersSource(io::Printer* printer) const; + void GenerateBuilderMembersSource(io::Printer* printer) const; + void GenerateMergingCodeSource(io::Printer* printer) const; + void GenerateBuildingCodeSource(io::Printer* printer) const; + void GenerateParsingCodeSource(io::Printer* printer) const; + void GenerateSerializationCodeSource(io::Printer* printer) const; + void GenerateSerializedSizeCodeSource(io::Printer* printer) const; + void GenerateDescriptionCodeSource(io::Printer* printer) const; + void GenerateIsEqualCodeSource(io::Printer* printer) const; + void GenerateHashCodeSource(io::Printer* printer) const; + + private: + const FieldDescriptor* descriptor_; + map variables_; + + GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedPrimitiveFieldGenerator); + }; + } // namespace swift + } // namespace compiler + } // namespace protobuf } // namespace google #endif // SWIFT_PRIMITIVE_FIELD_H