From c2916a1e0162d6412ccce4abdbbb61ec48e20382 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 22 Apr 2026 12:19:26 +0000 Subject: [PATCH 1/4] Update dependency com.diffplug.spotless:spotless-plugin-gradle to v8 --- gradle/libs.versions.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 51224f6078..c66dc5e61d 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -84,7 +84,7 @@ pluginz-dokka = { module = "org.jetbrains.dokka:dokka-gradle-plugin", version.re pluginz-kotlin = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } pluginz-kotlinSerialization = { module = "org.jetbrains.kotlin:kotlin-serialization", version.ref = "kotlin" } pluginz-shadow = { module = "com.gradleup.shadow:shadow-gradle-plugin", version = "8.3.10" } -pluginz-spotless = { module = "com.diffplug.spotless:spotless-plugin-gradle", version = "7.2.1" } +pluginz-spotless = { module = "com.diffplug.spotless:spotless-plugin-gradle", version = "8.4.0" } pluginz-buildConfig = { module = "com.github.gmazzo:gradle-buildconfig-plugin", version = "3.1.0" } protobuf-gradlePlugin = { module = "com.google.protobuf:protobuf-gradle-plugin", version.ref = "protobufGradlePlugin" } protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } From ad98041ac49e9355326ea3b2daac57c7eed6076e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Wed, 22 Apr 2026 13:49:36 +0100 Subject: [PATCH 2/4] Ktlint bump to please Spotless --- gradle/libs.versions.toml | 2 +- .../com/squareup/wire/ReverseProtoWriter.kt | 28 +++++++++++-------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c66dc5e61d..0f35707ede 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -17,7 +17,7 @@ kotlin = "2.2.21" # Set to lower version than KGP version to maximize compatibility kotlinCoreLibrariesVersion = "2.0.21" kotlinpoet = "2.3.0" -ktlint = "0.48.2" +ktlint = "1.5.0" moshi = "1.15.2" okhttp = "5.3.2" okio = "3.17.0" diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt index 2b8ca48090..eff10c6808 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt @@ -154,20 +154,20 @@ class ReverseProtoWriter { c < 0x800 -> { // Emit a 11-bit character with 2 bytes. require(2) - /* ktlint-disable no-multi-spaces */ + // @formatter:off array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx array[--arrayLimit] = (c shr 6 or 0xc0).toByte() // 110xxxxx - /* ktlint-enable no-multi-spaces */ + // @formatter:on } c < 0xd800 || c > 0xdfff -> { // Emit a 16-bit character with 3 bytes. require(3) - /* ktlint-disable no-multi-spaces */ + // @formatter:off array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx array[--arrayLimit] = (c shr 6 and 0x3f or 0x80).toByte() // 10xxxxxx array[--arrayLimit] = (c shr 12 or 0xe0).toByte() // 1110xxxx - /* ktlint-enable no-multi-spaces */ + // @formatter:on } else -> { @@ -187,12 +187,12 @@ class ReverseProtoWriter { // Emit a 21-bit character with 4 bytes. require(4) - /* ktlint-disable no-multi-spaces */ + // @formatter:off array[--arrayLimit] = (codePoint and 0x3f or 0x80).toByte() // 10yyyyyy array[--arrayLimit] = (codePoint shr 6 and 0x3f or 0x80).toByte() // 10xxyyyy array[--arrayLimit] = (codePoint shr 12 and 0x3f or 0x80).toByte() // 10xxxxxx array[--arrayLimit] = (codePoint shr 18 or 0xf0).toByte() // 11110xxx - /* ktlint-enable no-multi-spaces */ + // @formatter:on } } } @@ -254,10 +254,12 @@ class ReverseProtoWriter { require(4) arrayLimit -= 4 var offset = arrayLimit - array[offset++] = (value and 0xff).toByte() // ktlint-disable no-multi-spaces - array[offset++] = (value ushr 8 and 0xff).toByte() // ktlint-disable no-multi-spaces + // @formatter:off + array[offset++] = (value and 0xff).toByte() + array[offset++] = (value ushr 8 and 0xff).toByte() array[offset++] = (value ushr 16 and 0xff).toByte() - array[offset ] = (value ushr 24 and 0xff).toByte() // ktlint-disable no-multi-spaces + array[offset ] = (value ushr 24 and 0xff).toByte() + // @formatter:on } /** Write a little-endian 64-bit integer. */ @@ -265,14 +267,16 @@ class ReverseProtoWriter { require(8) arrayLimit -= 8 var offset = arrayLimit - array[offset++] = (value and 0xffL).toByte() // ktlint-disable no-multi-spaces - array[offset++] = (value ushr 8 and 0xffL).toByte() // ktlint-disable no-multi-spaces + // @formatter:off + array[offset++] = (value and 0xffL).toByte() + array[offset++] = (value ushr 8 and 0xffL).toByte() array[offset++] = (value ushr 16 and 0xffL).toByte() array[offset++] = (value ushr 24 and 0xffL).toByte() array[offset++] = (value ushr 32 and 0xffL).toByte() array[offset++] = (value ushr 40 and 0xffL).toByte() array[offset++] = (value ushr 48 and 0xffL).toByte() - array[offset ] = (value ushr 56 and 0xffL).toByte() // ktlint-disable no-multi-spaces + array[offset ] = (value ushr 56 and 0xffL).toByte() + // @formatter:on } private companion object { From c7999b11396bd22eb856cfb1497c70018c7fd8ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Wed, 22 Apr 2026 17:29:12 +0100 Subject: [PATCH 3/4] Formatting some code --- .../squareup/wire/benchmarks/SampleData.kt | 42 +++++++++---------- 1 file changed, 19 insertions(+), 23 deletions(-) diff --git a/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt b/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt index d62d005e9d..1fefdaa232 100644 --- a/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt +++ b/wire-benchmarks/src/main/kotlin/com/squareup/wire/benchmarks/SampleData.kt @@ -64,17 +64,15 @@ object SampleData { """.trimMargin() @JvmStatic - fun newMediumValueWire(): EmailSearchResponseWire { - return EmailSearchResponseWire( - query = recipientDisplayName, - results = listOf( - EmailThreadWire( - subject = subject, - messages = listOf(newEmailMessageWire()), - ), + fun newMediumValueWire(): EmailSearchResponseWire = EmailSearchResponseWire( + query = recipientDisplayName, + results = listOf( + EmailThreadWire( + subject = subject, + messages = listOf(newEmailMessageWire()), ), - ) - } + ), + ) private fun newEmailMessageWire() = EmailMessageWire( sent_at = sentAt, @@ -95,19 +93,17 @@ object SampleData { ) @JvmStatic - fun newMediumValueProtobuf(): EmailSearchResponseProtobuf { - return EmailSearchResponseProtobuf.newBuilder() - .apply { - query = recipientDisplayName - addResults( - EmailThreadProtobuf.newBuilder() - .apply { - subject = SampleData.subject - addMessages(newEmailMessageProtobuf()) - }.build(), - ) - }.build() - } + fun newMediumValueProtobuf(): EmailSearchResponseProtobuf = EmailSearchResponseProtobuf.newBuilder() + .apply { + query = recipientDisplayName + addResults( + EmailThreadProtobuf.newBuilder() + .apply { + subject = SampleData.subject + addMessages(newEmailMessageProtobuf()) + }.build(), + ) + }.build() private fun newEmailMessageProtobuf() = EmailMessageProtobuf.newBuilder() .apply { From 1159dd5d5911db1100fa20bbf6896fcd8d4b65f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Quenaudon?= Date: Wed, 22 Apr 2026 19:45:28 +0100 Subject: [PATCH 4/4] Code is formatted --- .../squareup/wire/whiteboard/MainActivity.kt | 4 +- .../wire/whiteboard/WhiteboardGrpcAction.kt | 4 +- .../java/com/squareup/wire/WireCompiler.kt | 4 +- .../java/com/squareup/wire/schema/Target.kt | 214 ++++---- .../squareup/wire/WireCompilerErrorTest.kt | 6 +- .../com/squareup/wire/schema/LinkerTest.kt | 3 +- .../squareup/wire/schema/MarkdownHandler.kt | 28 +- .../com/squareup/wire/schema/WireRunTest.kt | 3 +- .../com/squareup/wire/gradle/WireExtension.kt | 6 +- .../com/squareup/wire/gradle/WireInput.kt | 6 +- .../com/squareup/wire/gradle/WireOutput.kt | 30 +- .../com/squareup/wire/gradle/WirePlugin.kt | 10 +- .../com/squareup/wire/gradle/WireTask.kt | 4 +- .../squareup/wire/gradle/internal/projects.kt | 8 +- .../wire/gradle/kotlin/SourceRoots.kt | 16 +- .../kotlin/com/squareup/wire/GrpcStatus.kt | 3 +- .../com/squareup/wire/internal/GrpcDecoder.kt | 14 +- .../com/squareup/wire/internal/GrpcEncoder.kt | 14 +- .../com/squareup/wire/internal/platform.kt | 8 +- .../kotlin/com/squareup/wire/GrpcCalls.kt | 39 +- .../kotlin/com/squareup/wire/GrpcClient.kt | 16 +- .../kotlin/com/squareup/wire/GrpcResponse.kt | 3 +- .../wire/internal/BlockingMessageSource.kt | 40 +- .../internal/RealGrpcClientStreamingCall.kt | 3 +- .../internal/RealGrpcServerStreamingCall.kt | 7 +- .../kotlin/com/squareup/wire/internal/grpc.kt | 35 +- .../com/squareup/wire/internal/platform.kt | 8 +- .../com/squareup/wire/internal/platform.kt | 8 +- .../java/com/squareup/wire/GrpcClientTest.kt | 60 +-- .../squareup/wire/MockRouteGuideService.kt | 57 ++- .../com/squareup/wire/GsonJsonIntegration.kt | 4 +- .../squareup/wire/WireTypeAdapterFactory.kt | 4 +- .../squareup/wire/java/JavaGeneratorHelper.kt | 4 +- .../wire/java/JavaWithProfilesGenerator.kt | 4 +- .../squareup/wire/kotlin/KotlinGenerator.kt | 303 ++++++----- .../kotlin/KotlinWithProfilesGenerator.kt | 4 +- .../com/squareup/wire/MoshiJsonIntegration.kt | 3 +- .../com/squareup/wire/RedactingJsonAdapter.kt | 4 +- .../squareup/wire/WireJsonAdapterFactory.kt | 4 +- .../java/com/squareup/wire/InteropChecker.kt | 8 +- .../Proto2WireProtocCompatibilityTests.kt | 4 +- .../Proto3WireProtocCompatibilityTests.kt | 10 +- .../com/squareup/wire/ProtocStructHelper.kt | 26 +- .../com/squareup/wire/ProtocWrappersHelper.kt | 27 +- .../test/java/com/squareup/wire/StructTest.kt | 28 +- .../squareup/wire/UnwantedValueStripper.kt | 16 +- .../reflector/GrpcurlProto2InteropTest.kt | 33 +- .../reflector/GrpcurlProto3InteropTest.kt | 32 +- .../kotlin/com/squareup/wire/AnyMessage.kt | 12 +- .../kotlin/com/squareup/wire/EnumAdapter.kt | 8 +- .../kotlin/com/squareup/wire/FieldEncoding.kt | 6 +- .../kotlin/com/squareup/wire/OneOf.kt | 4 +- .../kotlin/com/squareup/wire/ProtoAdapter.kt | 128 ++--- .../wire/ProtoReader32AsProtoReader.kt | 3 +- .../kotlin/com/squareup/wire/ProtoWriter.kt | 16 +- .../com/squareup/wire/ReverseProtoWriter.kt | 28 +- .../squareup/wire/internal/ImmutableList.kt | 5 +- .../com/squareup/wire/internal/Internal.kt | 104 ++-- .../wire/internal/MutableOnWriteList.kt | 4 +- .../wire/internal/RuntimeMessageAdapter.kt | 4 +- .../squareup/wire/ReverseProtoWriterTest.kt | 12 +- .../com/squareup/wire/AndroidMessage.kt | 10 +- .../kotlin/com/squareup/wire/Duration.kt | 4 +- .../kotlin/com/squareup/wire/Instant.kt | 4 +- .../squareup/wire/KotlinConstructorBuilder.kt | 24 +- .../kotlin/com/squareup/wire/ProtoAdapter.kt | 111 ++--- .../com/squareup/wire/RuntimeEnumAdapter.kt | 6 +- .../com/squareup/wire/internal/-Platform.kt | 34 +- .../wire/internal/EnumJsonFormatter.kt | 14 +- .../squareup/wire/internal/FieldBinding.kt | 64 ++- .../wire/internal/InstantJsonFormatter.kt | 4 +- .../squareup/wire/internal/JsonIntegration.kt | 80 ++- .../com/squareup/wire/internal/reflection.kt | 12 +- .../kotlin/com/squareup/wire/ProtoAdapter.kt | 56 +-- .../com/squareup/wire/internal/-Platform.kt | 30 +- .../kotlin/com/squareup/wire/SchemaBuilder.kt | 12 +- .../wire/recipes/LogToWireLoggerHandler.kt | 4 +- .../squareup/wire/recipes/MarkdownHandler.kt | 24 +- .../com/squareup/wire/schema/CoreLoader.kt | 22 +- .../com/squareup/wire/schema/CycleChecker.kt | 92 ++-- .../com/squareup/wire/schema/EnumConstant.kt | 25 +- .../com/squareup/wire/schema/EnumType.kt | 40 +- .../com/squareup/wire/schema/Extensions.kt | 6 +- .../kotlin/com/squareup/wire/schema/Field.kt | 8 +- .../kotlin/com/squareup/wire/schema/Linker.kt | 8 +- .../com/squareup/wire/schema/Location.kt | 8 +- .../com/squareup/wire/schema/MarkSet.kt | 7 +- .../com/squareup/wire/schema/MessageType.kt | 34 +- .../kotlin/com/squareup/wire/schema/OneOf.kt | 21 +- .../com/squareup/wire/schema/Options.kt | 138 +++-- .../com/squareup/wire/schema/ProtoFile.kt | 45 +- .../com/squareup/wire/schema/ProtoMember.kt | 3 +- .../com/squareup/wire/schema/ProtoType.kt | 11 +- .../kotlin/com/squareup/wire/schema/Pruner.kt | 6 +- .../com/squareup/wire/schema/PruningRules.kt | 14 +- .../com/squareup/wire/schema/Reserved.kt | 6 +- .../kotlin/com/squareup/wire/schema/Root.kt | 22 +- .../kotlin/com/squareup/wire/schema/Rpc.kt | 48 +- .../kotlin/com/squareup/wire/schema/Schema.kt | 8 +- .../squareup/wire/schema/SchemaException.kt | 7 +- .../com/squareup/wire/schema/SchemaHandler.kt | 8 +- .../com/squareup/wire/schema/SchemaLoader.kt | 4 +- .../wire/schema/SchemaProtoAdapterFactory.kt | 24 +- .../com/squareup/wire/schema/Service.kt | 31 +- .../com/squareup/wire/schema/SyntaxRules.kt | 50 +- .../kotlin/com/squareup/wire/schema/Type.kt | 20 +- .../com/squareup/wire/schema/WireRun.kt | 4 +- .../schema/internal/CommonSchemaLoader.kt | 12 +- .../wire/schema/internal/SchemaEncoder.kt | 25 +- .../wire/schema/internal/TypeMover.kt | 22 +- .../com/squareup/wire/schema/internal/Util.kt | 9 +- .../schema/internal/parser/FieldElement.kt | 38 +- .../internal/parser/ProtoFileElement.kt | 4 +- .../schema/internal/parser/ProtoParser.kt | 8 +- .../schema/internal/parser/SyntaxReader.kt | 86 ++-- .../com/squareup/wire/schema/Assertions.kt | 4 +- .../wire/schema/internal/DagCheckerTest.kt | 6 +- .../schema/internal/parser/ProtoParserTest.kt | 1 + .../com/squareup/wire/schema/Multimap.kt | 4 +- .../com/squareup/wire/schema/SchemaLoader.kt | 4 +- .../squareup/wire/schema/EventListeners.kt | 8 +- .../com/squareup/wire/schema/Profile.kt | 7 +- .../com/squareup/wire/schema/SchemaLoader.kt | 4 +- .../com/squareup/wire/schema/WireLoggers.kt | 12 +- .../wire/schema/internal/JvmLanguages.kt | 24 +- .../wire/schema/internal/fileSystems.kt | 18 +- .../wire/schema/ManifestPartitionTest.kt | 6 +- .../com/squareup/wire/schema/PrunerTest.kt | 1 + .../com/squareup/wire/schema/Multimap.kt | 4 +- .../com/squareup/wire/schema/SchemaLoader.kt | 4 +- .../com/squareup/wire/swift/SwiftGenerator.kt | 470 +++++++++--------- .../com/squareup/wire/schema/SchemaHelpers.kt | 4 +- .../kotlin/com/squareup/wire/testing/files.kt | 14 +- .../wire/testing/UnwantedValueStripper.kt | 16 +- .../kotlin/com/squareup/wire/OneOfTest.kt | 3 + .../kotlin/com/squareup/wire/TestAllTypes.kt | 4 +- .../com/squareup/wire/TestAllTypesData.kt | 4 + .../com/squareup/wire/UnknownFieldsTest.kt | 1 + 138 files changed, 1530 insertions(+), 2023 deletions(-) diff --git a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt index 0c2515ff3c..ff1ac87e92 100644 --- a/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt +++ b/samples/wire-grpc-sample/client/src/main/java/com/squareup/wire/whiteboard/MainActivity.kt @@ -33,7 +33,9 @@ import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -class MainActivity : ComponentActivity(), OnBoardEventListener { +class MainActivity : + ComponentActivity(), + OnBoardEventListener { private lateinit var sendCommandChannel: SendChannel private lateinit var receiveUpdateChannel: ReceiveChannel private lateinit var whiteboardView: WhiteboardView diff --git a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt index 56f0d79336..a10125e6b7 100644 --- a/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt +++ b/samples/wire-grpc-sample/server/src/main/java/com/squareup/wire/whiteboard/WhiteboardGrpcAction.kt @@ -23,7 +23,9 @@ import javax.inject.Singleton import misk.web.actions.WebAction @Singleton -class WhiteboardGrpcAction : WebAction, WhiteboardWhiteboardBlockingServer { +class WhiteboardGrpcAction : + WebAction, + WhiteboardWhiteboardBlockingServer { val clients = mutableListOf() val points = mutableListOf() diff --git a/wire-compiler/src/main/java/com/squareup/wire/WireCompiler.kt b/wire-compiler/src/main/java/com/squareup/wire/WireCompiler.kt index 3a8b4912d0..0753f7f6aa 100644 --- a/wire-compiler/src/main/java/com/squareup/wire/WireCompiler.kt +++ b/wire-compiler/src/main/java/com/squareup/wire/WireCompiler.kt @@ -329,9 +329,7 @@ class WireCompiler internal constructor( fileSystem: NioFileSystem, logger: WireLogger, vararg args: String, - ): WireCompiler { - return forArgs(fileSystem.asOkioFileSystem(), logger, *args) - } + ): WireCompiler = forArgs(fileSystem.asOkioFileSystem(), logger, *args) @Throws(WireException::class) @JvmOverloads diff --git a/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt b/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt index 6561cb24a0..80d24ecf64 100644 --- a/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt +++ b/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt @@ -54,30 +54,26 @@ data class JavaTarget( /** If true, the constructor of all generated types will be non-public. */ val buildersOnly: Boolean = false, ) : Target() { - override fun newHandler(): SchemaHandler { - return JavaSchemaHandler( - android = android, - androidAnnotations = androidAnnotations, - compact = compact, - emitDeclaredOptions = emitDeclaredOptions, - emitAppliedOptions = emitAppliedOptions, - buildersOnly = buildersOnly, - ) - } + override fun newHandler(): SchemaHandler = JavaSchemaHandler( + android = android, + androidAnnotations = androidAnnotations, + compact = compact, + emitDeclaredOptions = emitDeclaredOptions, + emitAppliedOptions = emitAppliedOptions, + buildersOnly = buildersOnly, + ) override fun copyTarget( includes: List, excludes: List, exclusive: Boolean, outDirectory: String, - ): Target { - return copy( - includes = includes, - excludes = excludes, - exclusive = exclusive, - outDirectory = outDirectory, - ) - } + ): Target = copy( + includes = includes, + excludes = excludes, + exclusive = exclusive, + outDirectory = outDirectory, + ) } /** Generate `.kt` sources. */ @@ -164,41 +160,37 @@ data class KotlinTarget( */ private val makeImmutableCopies: Boolean = true, ) : Target() { - override fun newHandler(): SchemaHandler { - return KotlinSchemaHandler( - outDirectory = outDirectory, - android = android, - javaInterop = javaInterop, - emitDeclaredOptions = emitDeclaredOptions, - emitAppliedOptions = emitAppliedOptions, - rpcCallStyle = rpcCallStyle, - rpcRole = rpcRole, - singleMethodServices = singleMethodServices, - boxOneOfsMinSize = boxOneOfsMinSize, - nameSuffix = nameSuffix, - buildersOnly = buildersOnly, - escapeKotlinKeywords = escapeKotlinKeywords, - enumMode = enumMode, - emitProtoReader32 = emitProtoReader32, - mutableTypes = mutableTypes, - explicitStreamingCalls = explicitStreamingCalls, - makeImmutableCopies = makeImmutableCopies, - ) - } + override fun newHandler(): SchemaHandler = KotlinSchemaHandler( + outDirectory = outDirectory, + android = android, + javaInterop = javaInterop, + emitDeclaredOptions = emitDeclaredOptions, + emitAppliedOptions = emitAppliedOptions, + rpcCallStyle = rpcCallStyle, + rpcRole = rpcRole, + singleMethodServices = singleMethodServices, + boxOneOfsMinSize = boxOneOfsMinSize, + nameSuffix = nameSuffix, + buildersOnly = buildersOnly, + escapeKotlinKeywords = escapeKotlinKeywords, + enumMode = enumMode, + emitProtoReader32 = emitProtoReader32, + mutableTypes = mutableTypes, + explicitStreamingCalls = explicitStreamingCalls, + makeImmutableCopies = makeImmutableCopies, + ) override fun copyTarget( includes: List, excludes: List, exclusive: Boolean, outDirectory: String, - ): Target { - return copy( - includes = includes, - excludes = excludes, - exclusive = exclusive, - outDirectory = outDirectory, - ) - } + ): Target = copy( + includes = includes, + excludes = excludes, + exclusive = exclusive, + outDirectory = outDirectory, + ) } data class SwiftTarget( @@ -207,23 +199,19 @@ data class SwiftTarget( override val exclusive: Boolean = true, override val outDirectory: String, ) : Target() { - override fun newHandler(): SchemaHandler { - return SwiftSchemaHandler() - } + override fun newHandler(): SchemaHandler = SwiftSchemaHandler() override fun copyTarget( includes: List, excludes: List, exclusive: Boolean, outDirectory: String, - ): Target { - return copy( - includes = includes, - excludes = excludes, - exclusive = exclusive, - outDirectory = outDirectory, - ) - } + ): Target = copy( + includes = includes, + excludes = excludes, + exclusive = exclusive, + outDirectory = outDirectory, + ) } data class ProtoTarget( @@ -233,46 +221,44 @@ data class ProtoTarget( override val excludes: List = listOf() override val exclusive: Boolean = false - override fun newHandler(): SchemaHandler { - return object : SchemaHandler() { - override fun handle(schema: Schema, context: Context) { - context.fileSystem.createDirectories(context.outDirectory) - val outDirectory = context.outDirectory - - for (protoFile in schema.protoFiles) { - if (!context.inSourcePath(protoFile) || - protoFile.isEmpty() || - // We never emit the `.proto` files we are embedding within Wire. - isWireRuntimeProto(protoFile.location.path) - ) { - continue - } + override fun newHandler(): SchemaHandler = object : SchemaHandler() { + override fun handle(schema: Schema, context: Context) { + context.fileSystem.createDirectories(context.outDirectory) + val outDirectory = context.outDirectory + + for (protoFile in schema.protoFiles) { + if (!context.inSourcePath(protoFile) || + protoFile.isEmpty() || + // We never emit the `.proto` files we are embedding within Wire. + isWireRuntimeProto(protoFile.location.path) + ) { + continue + } + + val relativePath = protoFile.location.path + .substringBeforeLast("/", missingDelimiterValue = ".") + val outputDirectory = outDirectory / relativePath + val outputFilePath = outputDirectory / "${protoFile.name()}.proto" + context.logger.artifactHandled(outputDirectory, protoFile.location.path, "Proto") - val relativePath = protoFile.location.path - .substringBeforeLast("/", missingDelimiterValue = ".") - val outputDirectory = outDirectory / relativePath - val outputFilePath = outputDirectory / "${protoFile.name()}.proto" - context.logger.artifactHandled(outputDirectory, protoFile.location.path, "Proto") - - try { - context.fileSystem.createDirectories(outputFilePath.parent!!) - context.fileSystem.write(outputFilePath) { - writeUtf8(protoFile.toSchema()) - } - } catch (e: IOException) { - throw IOException("Error emitting $outputFilePath to $outDirectory", e) + try { + context.fileSystem.createDirectories(outputFilePath.parent!!) + context.fileSystem.write(outputFilePath) { + writeUtf8(protoFile.toSchema()) } + } catch (e: IOException) { + throw IOException("Error emitting $outputFilePath to $outDirectory", e) } } + } - private fun ProtoFile.isEmpty() = types.isEmpty() && services.isEmpty() && extendList.isEmpty() + private fun ProtoFile.isEmpty() = types.isEmpty() && services.isEmpty() && extendList.isEmpty() - override fun handle(type: Type, context: Context): Path? = null + override fun handle(type: Type, context: Context): Path? = null - override fun handle(service: Service, context: Context): List = listOf() + override fun handle(service: Service, context: Context): List = listOf() - override fun handle(extend: Extend, field: Field, context: Context): Path? = null - } + override fun handle(extend: Extend, field: Field, context: Context): Path? = null } override fun copyTarget( @@ -280,11 +266,9 @@ data class ProtoTarget( excludes: List, exclusive: Boolean, outDirectory: String, - ): Target { - return copy( - outDirectory = outDirectory, - ) - } + ): Target = copy( + outDirectory = outDirectory, + ) } data class CustomTarget( @@ -300,24 +284,20 @@ data class CustomTarget( excludes: List, exclusive: Boolean, outDirectory: String, - ): Target { - return this.copy( - includes = includes, - excludes = excludes, - exclusive = exclusive, - outDirectory = outDirectory, - ) - } - - override fun newHandler(): SchemaHandler { - return schemaHandlerFactory.create( - includes = includes, - excludes = excludes, - exclusive = exclusive, - outDirectory = outDirectory, - options = options, - ) - } + ): Target = this.copy( + includes = includes, + excludes = excludes, + exclusive = exclusive, + outDirectory = outDirectory, + ) + + override fun newHandler(): SchemaHandler = schemaHandlerFactory.create( + includes = includes, + excludes = excludes, + exclusive = exclusive, + outDirectory = outDirectory, + options = options, + ) } /** @@ -326,9 +306,7 @@ data class CustomTarget( * @param schemaHandlerFactoryClass a fully qualified class name for a class that implements * [SchemaHandler.Factory]. The class must have a no-arguments public constructor. */ -fun newSchemaHandler(schemaHandlerFactoryClass: String): SchemaHandler.Factory { - return ClassNameSchemaHandlerFactory(schemaHandlerFactoryClass) -} +fun newSchemaHandler(schemaHandlerFactoryClass: String): SchemaHandler.Factory = ClassNameSchemaHandlerFactory(schemaHandlerFactoryClass) /** * This schema handler factory is serializable (so Gradle can cache targets that use it). It works @@ -368,7 +346,5 @@ private class ClassNameSchemaHandlerFactory( exclusive: Boolean, outDirectory: String, options: Map, - ): SchemaHandler { - return delegate.create(includes, excludes, exclusive, outDirectory, options) - } + ): SchemaHandler = delegate.create(includes, excludes, exclusive, outDirectory, options) } diff --git a/wire-compiler/src/test/java/com/squareup/wire/WireCompilerErrorTest.kt b/wire-compiler/src/test/java/com/squareup/wire/WireCompilerErrorTest.kt index ea8bbae64c..99cd718bb0 100644 --- a/wire-compiler/src/test/java/com/squareup/wire/WireCompilerErrorTest.kt +++ b/wire-compiler/src/test/java/com/squareup/wire/WireCompilerErrorTest.kt @@ -212,9 +212,7 @@ class WireCompilerErrorTest { assertThat(readFile("/target/Simple.java")).doesNotContain("package") } - private fun readFile(path: String): String { - return fileSystem.read(path.toPath()) { - readUtf8() - } + private fun readFile(path: String): String = fileSystem.read(path.toPath()) { + readUtf8() } } diff --git a/wire-compiler/src/test/java/com/squareup/wire/schema/LinkerTest.kt b/wire-compiler/src/test/java/com/squareup/wire/schema/LinkerTest.kt index ecbb354876..7a8e4522bb 100644 --- a/wire-compiler/src/test/java/com/squareup/wire/schema/LinkerTest.kt +++ b/wire-compiler/src/test/java/com/squareup/wire/schema/LinkerTest.kt @@ -557,8 +557,7 @@ class LinkerTest { val schemaLoaderFileSystem = when { reverseSort -> { object : ForwardingFileSystem(fs) { - override fun listRecursively(dir: Path, followSymlinks: Boolean): Sequence = - super.listRecursively(dir, followSymlinks).toList().reversed().asSequence() + override fun listRecursively(dir: Path, followSymlinks: Boolean): Sequence = super.listRecursively(dir, followSymlinks).toList().reversed().asSequence() } } else -> fs diff --git a/wire-compiler/src/test/java/com/squareup/wire/schema/MarkdownHandler.kt b/wire-compiler/src/test/java/com/squareup/wire/schema/MarkdownHandler.kt index 97cbea8b87..45500b3598 100644 --- a/wire-compiler/src/test/java/com/squareup/wire/schema/MarkdownHandler.kt +++ b/wire-compiler/src/test/java/com/squareup/wire/schema/MarkdownHandler.kt @@ -24,24 +24,16 @@ class MarkdownHandlerFactory : SchemaHandler.Factory { exclusive: Boolean, outDirectory: String, options: Map, - ): SchemaHandler { - return MarkdownHandler() - } + ): SchemaHandler = MarkdownHandler() } /** This is a sample handler that writes text files that describe types. */ private class MarkdownHandler : SchemaHandler() { - override fun handle(type: Type, context: Context): Path { - return writeMarkdownFile(type.type, toMarkdown(type), context) - } + override fun handle(type: Type, context: Context): Path = writeMarkdownFile(type.type, toMarkdown(type), context) - override fun handle(service: Service, context: Context): List { - return listOf(writeMarkdownFile(service.type, toMarkdown(service), context)) - } + override fun handle(service: Service, context: Context): List = listOf(writeMarkdownFile(service.type, toMarkdown(service), context)) - override fun handle(extend: Extend, field: Field, context: Context): Path? { - return null - } + override fun handle(extend: Extend, field: Field, context: Context): Path? = null private fun writeMarkdownFile(protoType: ProtoType, markdown: String, context: Context): Path { val outDirectory = context.outDirectory @@ -62,21 +54,17 @@ private class MarkdownHandler : SchemaHandler() { return result } - private fun toMarkdown(type: Type): String { - return """ + private fun toMarkdown(type: Type): String = """ |# ${type.type.simpleName} | |${type.documentation} | - """.trimMargin() - } + """.trimMargin() - private fun toMarkdown(service: Service): String { - return """ + private fun toMarkdown(service: Service): String = """ |# ${service.type.simpleName} | |${service.documentation} | - """.trimMargin() - } + """.trimMargin() } diff --git a/wire-compiler/src/test/java/com/squareup/wire/schema/WireRunTest.kt b/wire-compiler/src/test/java/com/squareup/wire/schema/WireRunTest.kt index 5edc139d9d..4f174671d8 100644 --- a/wire-compiler/src/test/java/com/squareup/wire/schema/WireRunTest.kt +++ b/wire-compiler/src/test/java/com/squareup/wire/schema/WireRunTest.kt @@ -1026,8 +1026,7 @@ class WireRunTest { override fun handle(service: Service, context: SchemaHandler.Context): List = listOf() - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = - null + override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = null } } } diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt index d4504f1e70..4ac090813e 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireExtension.kt @@ -197,11 +197,9 @@ open class WireExtension( action.execute(protoRootSet) } - internal fun addProtoSourceProtoRootSet() = - addProtoRootSet(protoSourceProtoRootSets, "protoSource") + internal fun addProtoSourceProtoRootSet() = addProtoRootSet(protoSourceProtoRootSets, "protoSource") - internal fun addProtoPathProtoRootSet() = - addProtoRootSet(protoPathProtoRootSets, "protoPath") + internal fun addProtoPathProtoRootSet() = addProtoRootSet(protoPathProtoRootSets, "protoPath") /** Creates a new uniquely-named [ProtoRootSet], adds it to [list], and returns it. */ private fun addProtoRootSet( diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt index ff13310f66..265729f540 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireInput.kt @@ -50,7 +50,11 @@ internal fun InputLocation.toLocations( base.isDirectory -> fileOperations.fileTree(base) else -> throw IllegalArgumentException( """ - |Invalid path string: "${if (base.startsWith(projectFile)) { base.relativeTo(projectFile) } else { base }}". + |Invalid path string: "${if (base.startsWith(projectFile)) { + base.relativeTo(projectFile) + } else { + base + }}". |For individual files, use the following syntax: |wire { | sourcePath { diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt index 02f10be937..216f70efa3 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireOutput.kt @@ -74,20 +74,18 @@ open class JavaOutput @Inject constructor() : WireOutput() { /** If true, the constructor of all generated types will be non-public. */ var buildersOnly: Boolean = false - override fun toTarget(outputDirectory: String): JavaTarget { - return JavaTarget( - includes = includes ?: listOf("*"), - excludes = excludes ?: listOf(), - exclusive = exclusive, - outDirectory = outputDirectory, - android = android, - androidAnnotations = androidAnnotations, - compact = compact, - emitDeclaredOptions = emitDeclaredOptions, - emitAppliedOptions = emitAppliedOptions, - buildersOnly = buildersOnly, - ) - } + override fun toTarget(outputDirectory: String): JavaTarget = JavaTarget( + includes = includes ?: listOf("*"), + excludes = excludes ?: listOf(), + exclusive = exclusive, + outDirectory = outputDirectory, + android = android, + androidAnnotations = androidAnnotations, + compact = compact, + emitDeclaredOptions = emitDeclaredOptions, + emitAppliedOptions = emitAppliedOptions, + buildersOnly = buildersOnly, + ) } open class KotlinOutput @Inject constructor() : WireOutput() { @@ -226,9 +224,7 @@ open class KotlinOutput @Inject constructor() : WireOutput() { } open class ProtoOutput @Inject constructor() : WireOutput() { - override fun toTarget(outputDirectory: String): ProtoTarget { - return ProtoTarget(outDirectory = outputDirectory) - } + override fun toTarget(outputDirectory: String): ProtoTarget = ProtoTarget(outDirectory = outputDirectory) } open class CustomOutput @Inject constructor() : WireOutput() { diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt index 3a5f0ce6d2..609bf47e1c 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WirePlugin.kt @@ -281,12 +281,10 @@ class WirePlugin : Plugin { } } - private fun wireRuntimeDependency(isInternalBuild: Boolean): Any { - return if (isInternalBuild) { - project.project(":wire-runtime") - } else { - project.dependencies.create("com.squareup.wire:wire-runtime:$wireVersion") - } + private fun wireRuntimeDependency(isInternalBuild: Boolean): Any = if (isInternalBuild) { + project.project(":wire-runtime") + } else { + project.dependencies.create("com.squareup.wire:wire-runtime:$wireVersion") } internal companion object { diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt index ddf227db49..c092d20462 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/WireTask.kt @@ -197,7 +197,5 @@ abstract class WireTask @Inject constructor( @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) - override fun getSource(): FileTree { - return super.getSource() - } + override fun getSource(): FileTree = super.getSource() } diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt index 94bd6273e8..786c87ce57 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/internal/projects.kt @@ -19,13 +19,9 @@ import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.jetbrains.kotlin.gradle.plugin.KotlinPlatformType -internal fun Project.targetDefaultOutputPath(): String { - return "$buildDir/generated/source/wire" -} +internal fun Project.targetDefaultOutputPath(): String = "$buildDir/generated/source/wire" -internal fun Project.libraryProtoOutputPath(): String { - return "$buildDir/wire/proto-sources" -} +internal fun Project.libraryProtoOutputPath(): String = "$buildDir/wire/proto-sources" internal fun protoProjectDependenciesJvmConfiguration(classLoader: ClassLoader): (Configuration) -> Unit { try { diff --git a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt index 53d5f2e2b8..c57f7dc400 100644 --- a/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt +++ b/wire-gradle-plugin/src/main/kotlin/com/squareup/wire/gradle/kotlin/SourceRoots.kt @@ -97,11 +97,9 @@ internal abstract class WireSource( val name: String, private val sourceSets: List, ) { - fun defaultSourceFolders(project: Project): Set { - return sourceSets.map { "src/$it/proto" } - .filter { path -> File(project.projectDir, path).exists() } - .toSet() - } + fun defaultSourceFolders(project: Project): Set = sourceSets.map { "src/$it/proto" } + .filter { path -> File(project.projectDir, path).exists() } + .toSet() abstract fun outputDir(project: Project): File @@ -131,9 +129,7 @@ private class JvmOrKmpSource( private val kotlinSourceSet: KotlinSourceSet?, private val javaSourceDirectorySet: SourceDirectorySet?, ) : WireSource(name, sourceSets) { - override fun outputDir(project: Project): File { - return File(project.targetDefaultOutputPath()) - } + override fun outputDir(project: Project): File = File(project.targetDefaultOutputPath()) override fun registerGeneratedSources( project: Project, @@ -172,9 +168,7 @@ private class AndroidSource( sourceSets: List, private val variant: Variant, ) : WireSource(name, sourceSets) { - override fun outputDir(project: Project): File { - return File(project.targetDefaultOutputPath(), name) - } + override fun outputDir(project: Project): File = File(project.targetDefaultOutputPath(), name) override fun registerGeneratedSources( project: Project, diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt index 6f904e8b08..dac9850981 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/GrpcStatus.kt @@ -93,7 +93,6 @@ class GrpcStatus private constructor( * Returns an instance with a well-known name (like "OK"), or a string like "STATUS_99" if the * code was not known when this was built. */ - fun get(status: Int): GrpcStatus = - INSTANCES.getOrNull(status) ?: GrpcStatus("STATUS_$status", status) + fun get(status: Int): GrpcStatus = INSTANCES.getOrNull(status) ?: GrpcStatus("STATUS_$status", status) } } diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt index ef311cf573..a8ed5471fa 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcDecoder.kt @@ -31,12 +31,10 @@ internal sealed class GrpcDecoder(val name: String) { } } -internal fun String.toGrpcDecoding(): GrpcDecoder { - return when (this) { - "identity" -> GrpcDecoder.IdentityGrpcDecoder - "gzip" -> GrpcDecoder.GzipGrpcDecoder - "deflate" -> throw ProtocolException("deflate not yet supported") - "snappy" -> throw ProtocolException("snappy not yet supported") - else -> throw ProtocolException("unsupported grpc-encoding: $this") - } +internal fun String.toGrpcDecoding(): GrpcDecoder = when (this) { + "identity" -> GrpcDecoder.IdentityGrpcDecoder + "gzip" -> GrpcDecoder.GzipGrpcDecoder + "deflate" -> throw ProtocolException("deflate not yet supported") + "snappy" -> throw ProtocolException("snappy not yet supported") + else -> throw ProtocolException("unsupported grpc-encoding: $this") } diff --git a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt index 5a998211f7..8c60fda994 100644 --- a/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt +++ b/wire-grpc-client/src/commonMain/kotlin/com/squareup/wire/internal/GrpcEncoder.kt @@ -31,12 +31,10 @@ internal sealed class GrpcEncoder(val name: String) { } } -internal fun String.toGrpcEncoder(): GrpcEncoder { - return when (this) { - "identity" -> GrpcEncoder.IdentityGrpcEncoder - "gzip" -> GrpcEncoder.GzipGrpcEncoder - "deflate" -> throw ProtocolException("deflate not yet supported") - "snappy" -> throw ProtocolException("snappy not yet supported") - else -> throw ProtocolException("unsupported grpc-encoding: $this") - } +internal fun String.toGrpcEncoder(): GrpcEncoder = when (this) { + "identity" -> GrpcEncoder.IdentityGrpcEncoder + "gzip" -> GrpcEncoder.GzipGrpcEncoder + "deflate" -> throw ProtocolException("deflate not yet supported") + "snappy" -> throw ProtocolException("snappy not yet supported") + else -> throw ProtocolException("unsupported grpc-encoding: $this") } diff --git a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt index f9b8c73806..287c698521 100644 --- a/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/jsMain/kotlin/com/squareup/wire/internal/platform.kt @@ -24,13 +24,9 @@ internal actual interface Call { actual fun execute(): GrpcResponse } -internal actual fun Sink.asGzip(): Sink { - throw UnsupportedOperationException("Gzip not implemented for JS") -} +internal actual fun Sink.asGzip(): Sink = throw UnsupportedOperationException("Gzip not implemented for JS") -internal actual fun Source.asGzip(): Source { - throw UnsupportedOperationException("Gzip not implemented for JS") -} +internal actual fun Source.asGzip(): Source = throw UnsupportedOperationException("Gzip not implemented for JS") internal actual fun Throwable.addSuppressed(other: Throwable) { } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt index 0de44d2f00..7d510a2de5 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcCalls.kt @@ -213,40 +213,35 @@ fun GrpcStreamingCall( return requestChannel.toMessageSink() to responseChannel.toMessageSource() } - override fun clone() = - GrpcStreamingCall(function).also { it.requestMetadata += requestMetadata } + override fun clone() = GrpcStreamingCall(function).also { it.requestMetadata += requestMetadata } } } @JvmName("grpcClientStreamingCall") fun GrpcClientStreamingCall( function: suspend ReceiveChannel.() -> R, -): GrpcClientStreamingCall = - GrpcStreamingCall { requests, responses -> - val response = requests.function() - if (response != Unit) { - responses.send(response) - } - }.asGrpcClientStreamingCall() +): GrpcClientStreamingCall = GrpcStreamingCall { requests, responses -> + val response = requests.function() + if (response != Unit) { + responses.send(response) + } +}.asGrpcClientStreamingCall() @JvmName("grpcServerStreamingCall") fun GrpcServerStreamingCall( function: suspend SendChannel.(S) -> Unit, -): GrpcServerStreamingCall = - GrpcStreamingCall { requests, responses -> - function(responses, requests.receive()) - }.asGrpcServerStreamingCall() +): GrpcServerStreamingCall = GrpcStreamingCall { requests, responses -> + function(responses, requests.receive()) +}.asGrpcServerStreamingCall() internal fun Channel.toMessageSource() = object : MessageSource { - override fun read(): E? { - return runBlocking { - try { - receiveCatching() - .onClosed { if (it != null) throw it } - .getOrNull() - } catch (e: Exception) { - throw IOException(e) - } + override fun read(): E? = runBlocking { + try { + receiveCatching() + .onClosed { if (it != null) throw it } + .getOrNull() + } catch (e: Exception) { + throw IOException(e) } } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt index 31c28a6d1b..c43b1f6123 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcClient.kt @@ -181,19 +181,11 @@ internal class WireGrpcClient internal constructor( internal val baseUrl: GrpcHttpUrl, internal val minMessageToCompress: Long, ) : GrpcClient() { - override fun newCall(method: GrpcMethod): GrpcCall { - return RealGrpcCall(this, method) - } + override fun newCall(method: GrpcMethod): GrpcCall = RealGrpcCall(this, method) - override fun newStreamingCall(method: GrpcMethod): GrpcStreamingCall { - return RealGrpcStreamingCall(this, method) - } + override fun newStreamingCall(method: GrpcMethod): GrpcStreamingCall = RealGrpcStreamingCall(this, method) - override fun newClientStreamingCall(method: GrpcMethod): GrpcClientStreamingCall { - return RealGrpcStreamingCall(this, method).asGrpcClientStreamingCall() - } + override fun newClientStreamingCall(method: GrpcMethod): GrpcClientStreamingCall = RealGrpcStreamingCall(this, method).asGrpcClientStreamingCall() - override fun newServerStreamingCall(method: GrpcMethod): GrpcServerStreamingCall { - return RealGrpcStreamingCall(this, method).asGrpcServerStreamingCall() - } + override fun newServerStreamingCall(method: GrpcMethod): GrpcServerStreamingCall = RealGrpcStreamingCall(this, method).asGrpcServerStreamingCall() } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt index 1bb8bfcdd8..9c6689006b 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/GrpcResponse.kt @@ -27,8 +27,7 @@ internal actual class GrpcResponse(private val response: Response) { fun header(name: String): String? = header(name, null) - actual fun header(name: String, defaultValue: String?): String? = - response.header(name, defaultValue) + actual fun header(name: String, defaultValue: String?): String? = response.header(name, defaultValue) /** * Returns the trailers after the HTTP response, which may be empty. It is an error to call this diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt index 6c9e81606a..653ddaff38 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/BlockingMessageSource.kt @@ -59,31 +59,29 @@ internal class BlockingMessageSource( } /** Read messages from the response body and write them to the deque. */ - fun readFromResponseBodyCallback(): Callback { - return object : Callback { - override fun onFailure(call: Call, e: IOException) { - queue.put(Failure(e)) - } - - override fun onResponse(call: Call, response: Response) { - try { - grpcCall.responseMetadata = response.headers.toMap() - response.use { - response.messageSource(responseAdapter).use { reader -> - while (true) { - val message = reader.read() ?: break - queue.put(message) - } + fun readFromResponseBodyCallback(): Callback = object : Callback { + override fun onFailure(call: Call, e: IOException) { + queue.put(Failure(e)) + } - val exception = response.grpcResponseToException() - if (exception != null) throw exception + override fun onResponse(call: Call, response: Response) { + try { + grpcCall.responseMetadata = response.headers.toMap() + response.use { + response.messageSource(responseAdapter).use { reader -> + while (true) { + val message = reader.read() ?: break + queue.put(message) } + + val exception = response.grpcResponseToException() + if (exception != null) throw exception } - queue.put(Complete) - } catch (e: IOException) { - call.cancel() // Break the request stream if the response stream breaks. - queue.put(Failure(e)) } + queue.put(Complete) + } catch (e: IOException) { + call.cancel() // Break the request stream if the response stream breaks. + queue.put(Failure(e)) } } } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcClientStreamingCall.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcClientStreamingCall.kt index 670c033397..55450ccc2e 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcClientStreamingCall.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcClientStreamingCall.kt @@ -96,5 +96,4 @@ internal class RealGrpcClientStreamingCall( override fun clone() = RealGrpcClientStreamingCall(callDelegate.clone(), method) } -internal fun GrpcStreamingCall.asGrpcClientStreamingCall() = - RealGrpcClientStreamingCall(this, method) +internal fun GrpcStreamingCall.asGrpcClientStreamingCall() = RealGrpcClientStreamingCall(this, method) diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcServerStreamingCall.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcServerStreamingCall.kt index b74aace69c..50338d2b5c 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcServerStreamingCall.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/RealGrpcServerStreamingCall.kt @@ -33,7 +33,9 @@ internal class RealGrpcServerStreamingCall( override var requestMetadata: Map get() = callDelegate.requestMetadata - set(value) { callDelegate.requestMetadata = value } + set(value) { + callDelegate.requestMetadata = value + } override val responseMetadata: Map? get() = callDelegate.responseMetadata @@ -65,5 +67,4 @@ internal class RealGrpcServerStreamingCall( } } -internal fun GrpcStreamingCall.asGrpcServerStreamingCall() = - RealGrpcServerStreamingCall(this, method) +internal fun GrpcStreamingCall.asGrpcServerStreamingCall() = RealGrpcServerStreamingCall(this, method) diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt index 94f69f4c62..7c894a93ab 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/grpc.kt @@ -43,21 +43,19 @@ internal fun newRequestBody( minMessageToCompress: Long, requestAdapter: ProtoAdapter, onlyMessage: S, -): RequestBody { - return object : RequestBody() { - override fun contentType() = APPLICATION_GRPC_MEDIA_TYPE - - override fun writeTo(sink: BufferedSink) { - val grpcMessageSink = GrpcMessageSink( - sink = sink, - minMessageToCompress = minMessageToCompress, - messageAdapter = requestAdapter, - callForCancel = null, - grpcEncoding = "gzip", - ) - grpcMessageSink.use { - it.write(onlyMessage) - } +): RequestBody = object : RequestBody() { + override fun contentType() = APPLICATION_GRPC_MEDIA_TYPE + + override fun writeTo(sink: BufferedSink) { + val grpcMessageSink = GrpcMessageSink( + sink = sink, + minMessageToCompress = minMessageToCompress, + messageAdapter = requestAdapter, + callForCancel = null, + grpcEncoding = "gzip", + ) + grpcMessageSink.use { + it.write(onlyMessage) } } } @@ -66,9 +64,7 @@ internal fun newRequestBody( * Returns a new duplex request body that allows us to write request messages even after the * response status, headers, and body have been received. */ -internal fun newDuplexRequestBody(): PipeDuplexRequestBody { - return PipeDuplexRequestBody(APPLICATION_GRPC_MEDIA_TYPE, pipeMaxBufferSize = 1024 * 1024) -} +internal fun newDuplexRequestBody(): PipeDuplexRequestBody = PipeDuplexRequestBody(APPLICATION_GRPC_MEDIA_TYPE, pipeMaxBufferSize = 1024 * 1024) /** Writes messages to the request body. */ internal fun PipeDuplexRequestBody.messageSink( @@ -193,7 +189,8 @@ private fun Response.checkGrpcResponse() { if (code != 200 || contentType == null || contentType.type != "application" || - contentType.subtype != "grpc" && contentType.subtype != "grpc+proto" + contentType.subtype != "grpc" && + contentType.subtype != "grpc+proto" ) { throw IOException("expected gRPC but was HTTP status=$code, content-type=$contentType") } diff --git a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt index 79eda6ab73..ab785f81ca 100644 --- a/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/jvmMain/kotlin/com/squareup/wire/internal/platform.kt @@ -29,12 +29,10 @@ internal actual interface Call { actual fun execute(): GrpcResponse } -internal fun okhttp3.Call.toWireCall(): Call { - return object : Call { - override fun cancel() = this@toWireCall.cancel() +internal fun okhttp3.Call.toWireCall(): Call = object : Call { + override fun cancel() = this@toWireCall.cancel() - override fun execute(): GrpcResponse = GrpcResponse(this@toWireCall.execute()) - } + override fun execute(): GrpcResponse = GrpcResponse(this@toWireCall.execute()) } @Suppress("NOTHING_TO_INLINE") diff --git a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt index 7af51a924f..baf541f30c 100644 --- a/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt +++ b/wire-grpc-client/src/nativeMain/kotlin/com/squareup/wire/internal/platform.kt @@ -24,13 +24,9 @@ internal actual interface Call { actual fun execute(): GrpcResponse } -internal actual fun Sink.asGzip(): Sink { - throw UnsupportedOperationException("Gzip not implemented for native") -} +internal actual fun Sink.asGzip(): Sink = throw UnsupportedOperationException("Gzip not implemented for native") -internal actual fun Source.asGzip(): Source { - throw UnsupportedOperationException("Gzip not implemented for native") -} +internal actual fun Source.asGzip(): Source = throw UnsupportedOperationException("Gzip not implemented for native") internal actual fun Throwable.addSuppressed(other: Throwable) { } diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt index 9388b1af61..747cd1ced5 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/GrpcClientTest.kt @@ -239,9 +239,7 @@ class GrpcClientTest { grpcCall.enqueue( Point(latitude = 5, longitude = 6), object : GrpcCall.Callback { - override fun onFailure(call: GrpcCall, exception: IOException) { - throw AssertionError() - } + override fun onFailure(call: GrpcCall, exception: IOException): Unit = throw AssertionError() override fun onSuccess(call: GrpcCall, response: Feature) { feature = response @@ -994,9 +992,7 @@ class GrpcClientTest { grpcCall.enqueue( Point(latitude = 5, longitude = 6), object : GrpcCall.Callback { - override fun onFailure(call: GrpcCall, exception: IOException) { - throw AssertionError() - } + override fun onFailure(call: GrpcCall, exception: IOException): Unit = throw AssertionError() override fun onSuccess(call: GrpcCall, response: Feature) { feature = response @@ -1112,9 +1108,7 @@ class GrpcClientTest { latch.countDown() } - override fun onSuccess(call: GrpcCall, response: Feature) { - throw AssertionError() - } + override fun onSuccess(call: GrpcCall, response: Feature): Unit = throw AssertionError() }, ) @@ -1125,15 +1119,13 @@ class GrpcClientTest { @Test fun responseStatusIsNot200() { interceptor = object : Interceptor { - override fun intercept(chain: Chain): Response { - return Response.Builder() - .request(chain.request()) - .protocol(HTTP_2) - .code(500) - .message("internal server error") - .body(ByteString.EMPTY.toResponseBody("application/grpc".toMediaType())) - .build() - } + override fun intercept(chain: Chain): Response = Response.Builder() + .request(chain.request()) + .protocol(HTTP_2) + .code(500) + .message("internal server error") + .body(ByteString.EMPTY.toResponseBody("application/grpc".toMediaType())) + .build() } runBlocking { @@ -1152,15 +1144,13 @@ class GrpcClientTest { @Test fun responseContentTypeIsNotGrpc() { interceptor = object : Interceptor { - override fun intercept(chain: Chain): Response { - return Response.Builder() - .request(chain.request()) - .protocol(HTTP_2) - .code(200) - .message("ok") - .body(ByteString.EMPTY.toResponseBody("text/plain".toMediaType())) - .build() - } + override fun intercept(chain: Chain): Response = Response.Builder() + .request(chain.request()) + .protocol(HTTP_2) + .code(200) + .message("ok") + .body(ByteString.EMPTY.toResponseBody("text/plain".toMediaType())) + .build() } runBlocking { @@ -1894,13 +1884,13 @@ class GrpcClientTest { class IncompatibleRouteGuideClient( private val client: GrpcClient, ) { - fun RouteChat(): GrpcCall = - client.newCall( - GrpcMethod( - path = "/routeguide.RouteGuide/RouteChat", - requestAdapter = RouteNote.ADAPTER, - responseAdapter = RouteNote.ADAPTER, - ), - ) + @Suppress("ktlint:standard:function-naming") + fun RouteChat(): GrpcCall = client.newCall( + GrpcMethod( + path = "/routeguide.RouteGuide/RouteChat", + requestAdapter = RouteNote.ADAPTER, + responseAdapter = RouteNote.ADAPTER, + ), + ) } } diff --git a/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt b/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt index a72a9f6aff..0185c23d4e 100644 --- a/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt +++ b/wire-grpc-tests/src/test/java/com/squareup/wire/MockRouteGuideService.kt @@ -52,7 +52,10 @@ import routeguide.RouteGuideProto.RouteSummary * An assertive scriptable implementation of the [RouteGuideGrpc] gRPC service. Receiving and * sending actions can be added via the [MockRouteGuideService.enqueue] method. */ -class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, ServerInterceptor { +class MockRouteGuideService : + RouteGuideGrpc.RouteGuideImplBase(), + TestRule, + ServerInterceptor { private lateinit var server: Server private lateinit var streamObserver: StreamObserver private var lastRequestHeaders: Metadata? = null @@ -145,21 +148,19 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser } } - override fun apply(base: Statement, description: Description): Statement { - return object : Statement() { - override fun evaluate() { - server = ServerBuilder.forPort(0) - .intercept(this@MockRouteGuideService) - .addService(this@MockRouteGuideService) - .build() - server.start() - try { - base.evaluate() - } finally { - server.shutdown() - } - server.awaitTermination() + override fun apply(base: Statement, description: Description): Statement = object : Statement() { + override fun evaluate() { + server = ServerBuilder.forPort(0) + .intercept(this@MockRouteGuideService) + .addService(this@MockRouteGuideService) + .build() + server.start() + try { + base.evaluate() + } finally { + server.shutdown() } + server.awaitTermination() } } @@ -250,24 +251,22 @@ class MockRouteGuideService : RouteGuideGrpc.RouteGuideImplBase(), TestRule, Ser ) } - private fun createAssertingStreamObserver(): StreamObserver { - return object : StreamObserver { - override fun onNext(value: T) { - assertNextActionAndProcessScript { - assertThat(it).isEqualTo(Action.ReceiveMessage(value)) - } + private fun createAssertingStreamObserver(): StreamObserver = object : StreamObserver { + override fun onNext(value: T) { + assertNextActionAndProcessScript { + assertThat(it).isEqualTo(Action.ReceiveMessage(value)) } + } - override fun onError(t: Throwable?) { - assertNextActionAndProcessScript { - assertThat(it).isEqualTo(Action.ReceiveError) - } + override fun onError(t: Throwable?) { + assertNextActionAndProcessScript { + assertThat(it).isEqualTo(Action.ReceiveError) } + } - override fun onCompleted() { - assertNextActionAndProcessScript { - assertThat(it).isEqualTo(Action.ReceiveComplete) - } + override fun onCompleted() { + assertNextActionAndProcessScript { + assertThat(it).isEqualTo(Action.ReceiveComplete) } } } diff --git a/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt b/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt index d9ced0a6bd..60c950088a 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/GsonJsonIntegration.kt @@ -65,9 +65,7 @@ internal object GsonJsonIntegration : JsonIntegration>() } } - override fun read(reader: JsonReader): T { - return delegate.read(reader) - } + override fun read(reader: JsonReader): T = delegate.read(reader) } } diff --git a/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt b/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt index 0f35b18e48..c907bb85bf 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/WireTypeAdapterFactory.kt @@ -74,9 +74,7 @@ class WireTypeAdapterFactory @JvmOverloads constructor( * Returns a new WireTypeAdapterFactory that can encode the messages for [adapter] if they're * used with [AnyMessage]. */ - fun plus(adapter: ProtoAdapter<*>): WireTypeAdapterFactory { - return plus(listOf(adapter)) - } + fun plus(adapter: ProtoAdapter<*>): WireTypeAdapterFactory = plus(listOf(adapter)) @Suppress("UNCHECKED_CAST") override fun create(gson: Gson, type: TypeToken): TypeAdapter? { diff --git a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt index 7e9e7625db..41bd6f3ee2 100644 --- a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt +++ b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaGeneratorHelper.kt @@ -43,9 +43,7 @@ internal class JavaGeneratorHelper(private val schema: Schema) { return this } - private fun profile(profileName: String?): Profile { - return if (profileName == null) Profile() else profiles["$profileName.wire"]!! - } + private fun profile(profileName: String?): Profile = if (profileName == null) Profile() else profiles["$profileName.wire"]!! @Throws(IOException::class) @JvmOverloads diff --git a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt index 27cf240a5e..4138166085 100644 --- a/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt +++ b/wire-java-generator/src/test/java/com/squareup/wire/java/JavaWithProfilesGenerator.kt @@ -43,9 +43,7 @@ internal class JavaWithProfilesGenerator(private val schema: Schema) { return this } - private fun profile(profileName: String?): Profile { - return if (profileName == null) Profile() else profiles["$profileName.wire"]!! - } + private fun profile(profileName: String?): Profile = if (profileName == null) Profile() else profiles["$profileName.wire"]!! @Throws(IOException::class) @JvmOverloads diff --git a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt index 1ebb58fd85..413d0b67ac 100644 --- a/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt +++ b/wire-kotlin-generator/src/main/java/com/squareup/wire/kotlin/KotlinGenerator.kt @@ -495,78 +495,72 @@ class KotlinGenerator private constructor( return funSpecBuilder.build() } - private fun writableStreamOf(typeName: TypeName): ParameterizedTypeName { - return when (rpcCallStyle) { - RpcCallStyle.SUSPENDING -> SendChannel::class.asClassName().parameterizedBy(typeName) - RpcCallStyle.BLOCKING -> MessageSink::class.asClassName().parameterizedBy(typeName) - } - } - - private fun readableStreamOf(typeName: TypeName): ParameterizedTypeName { - return when (rpcCallStyle) { - RpcCallStyle.SUSPENDING -> ReceiveChannel::class.asClassName().parameterizedBy(typeName) - RpcCallStyle.BLOCKING -> MessageSource::class.asClassName().parameterizedBy(typeName) - } - } - - private fun nameAllocator(message: Type): NameAllocator { - return nameAllocatorStore.getOrPut(message) { - NameAllocator(preallocateKeywords = !escapeKotlinKeywords).apply { - when (message) { - is EnumType -> { - newName("ADAPTER", "ADAPTER") - newName("ENUM_OPTIONS", "ENUM_OPTIONS") - message.constants.forEach { constant -> - val constantName = when (constant.name) { - // `name` and `ordinal` are private fields of all Kotlin enums. We are escaping them - // manually because KotlinPoet does not escape them. - "name", "ordinal" -> constant.name + "_" - else -> constant.name - } - newName(constantName, constant) + private fun writableStreamOf(typeName: TypeName): ParameterizedTypeName = when (rpcCallStyle) { + RpcCallStyle.SUSPENDING -> SendChannel::class.asClassName().parameterizedBy(typeName) + RpcCallStyle.BLOCKING -> MessageSink::class.asClassName().parameterizedBy(typeName) + } + + private fun readableStreamOf(typeName: TypeName): ParameterizedTypeName = when (rpcCallStyle) { + RpcCallStyle.SUSPENDING -> ReceiveChannel::class.asClassName().parameterizedBy(typeName) + RpcCallStyle.BLOCKING -> MessageSource::class.asClassName().parameterizedBy(typeName) + } + + private fun nameAllocator(message: Type): NameAllocator = nameAllocatorStore.getOrPut(message) { + NameAllocator(preallocateKeywords = !escapeKotlinKeywords).apply { + when (message) { + is EnumType -> { + newName("ADAPTER", "ADAPTER") + newName("ENUM_OPTIONS", "ENUM_OPTIONS") + message.constants.forEach { constant -> + val constantName = when (constant.name) { + // `name` and `ordinal` are private fields of all Kotlin enums. We are escaping them + // manually because KotlinPoet does not escape them. + "name", "ordinal" -> constant.name + "_" + else -> constant.name } + newName(constantName, constant) } - is MessageType -> { - newName("unknownFields", "unknownFields") - newName("ADAPTER", "ADAPTER") - newName("adapter", "adapter") - newName("reader", "reader") - newName("Builder", "Builder") - newName("builder", "builder") - newName("MESSAGE_OPTIONS", "MESSAGE_OPTIONS") - - if (emitAndroid) { - newName("CREATOR", "CREATOR") - } - for (fieldOrOneOf in message.fieldsAndFlatOneOfFieldsAndBoxedOneOfs()) { - when (fieldOrOneOf) { - is Field -> { - if (fieldOrOneOf.name == fieldOrOneOf.type!!.simpleName || - hasEponymousType(schema, fieldOrOneOf) - ) { - newName(legacyQualifiedFieldName(fieldOrOneOf), fieldOrOneOf) - } else { - newName(fieldOrOneOf.name, fieldOrOneOf) - } + } + is MessageType -> { + newName("unknownFields", "unknownFields") + newName("ADAPTER", "ADAPTER") + newName("adapter", "adapter") + newName("reader", "reader") + newName("Builder", "Builder") + newName("builder", "builder") + newName("MESSAGE_OPTIONS", "MESSAGE_OPTIONS") + + if (emitAndroid) { + newName("CREATOR", "CREATOR") + } + for (fieldOrOneOf in message.fieldsAndFlatOneOfFieldsAndBoxedOneOfs()) { + when (fieldOrOneOf) { + is Field -> { + if (fieldOrOneOf.name == fieldOrOneOf.type!!.simpleName || + hasEponymousType(schema, fieldOrOneOf) + ) { + newName(legacyQualifiedFieldName(fieldOrOneOf), fieldOrOneOf) + } else { + newName(fieldOrOneOf.name, fieldOrOneOf) } - is OneOf -> { - val fieldName = newName(fieldOrOneOf.name, fieldOrOneOf) - val keysFieldName = boxedOneOfKeysFieldName(fieldName) - check(newName(keysFieldName) == keysFieldName) { - "unexpected name collision for keys set of boxed one of, ${fieldOrOneOf.name}" - } - newName(boxedOneOfClassName(fieldOrOneOf.name), boxedOneOfClassName(fieldOrOneOf.name)) - fieldOrOneOf.fields.forEach { field -> - val keyFieldName = boxedOneOfKeyFieldName(fieldOrOneOf.name, field.name) - newName(keyFieldName, keyFieldName) - } + } + is OneOf -> { + val fieldName = newName(fieldOrOneOf.name, fieldOrOneOf) + val keysFieldName = boxedOneOfKeysFieldName(fieldName) + check(newName(keysFieldName) == keysFieldName) { + "unexpected name collision for keys set of boxed one of, ${fieldOrOneOf.name}" + } + newName(boxedOneOfClassName(fieldOrOneOf.name), boxedOneOfClassName(fieldOrOneOf.name)) + fieldOrOneOf.fields.forEach { field -> + val keyFieldName = boxedOneOfKeyFieldName(fieldOrOneOf.name, field.name) + newName(keyFieldName, keyFieldName) } - else -> throw IllegalArgumentException("Unexpected element: $fieldOrOneOf") } + else -> throw IllegalArgumentException("Unexpected element: $fieldOrOneOf") } } - else -> {} } + else -> {} } } } @@ -670,21 +664,19 @@ class KotlinGenerator private constructor( return classBuilder.build() } - private fun generateInitializerFlatOneOfBlock(type: MessageType): CodeBlock { - return buildCodeBlock { - val nameAllocator = nameAllocator(type) - type.flatOneOfs() - .filter { oneOf -> oneOf.fields.size >= 2 } - .forEach { oneOf -> - val countNonNull = MemberName("com.squareup.wire.internal", "countNonNull") - // FIXME(egor): Revert back to function reference once KotlinPoet compiled with Kotlin - // 1.4 is released. See https://youtrack.jetbrains.com/issue/KT-37435. - val fieldNames = oneOf.fields.joinToString(", ") { field -> nameAllocator[field] } - beginControlFlow("require(%M(%L)·<=·1)", countNonNull, fieldNames) - addStatement("%S", "At most one of $fieldNames may be non-null") - endControlFlow() - } - } + private fun generateInitializerFlatOneOfBlock(type: MessageType): CodeBlock = buildCodeBlock { + val nameAllocator = nameAllocator(type) + type.flatOneOfs() + .filter { oneOf -> oneOf.fields.size >= 2 } + .forEach { oneOf -> + val countNonNull = MemberName("com.squareup.wire.internal", "countNonNull") + // FIXME(egor): Revert back to function reference once KotlinPoet compiled with Kotlin + // 1.4 is released. See https://youtrack.jetbrains.com/issue/KT-37435. + val fieldNames = oneOf.fields.joinToString(", ") { field -> nameAllocator[field] } + beginControlFlow("require(%M(%L)·<=·1)", countNonNull, fieldNames) + addStatement("%S", "At most one of $fieldNames may be non-null") + endControlFlow() + } } private fun generateNewBuilderMethod(type: MessageType, builderClassName: ClassName): FunSpec { @@ -1321,65 +1313,63 @@ class KotlinGenerator private constructor( message: MessageType, field: Field, schemaIndex: Int?, - ): AnnotationSpec { - return AnnotationSpec.builder(WireField::class) - .useSiteTarget(FIELD) - .addMember("tag = %L", field.tag) - .apply { - if (field.type!!.isMap) { - addMember("keyAdapter = %S", field.type!!.keyType!!.adapterString()) - addMember("adapter = %S", field.type!!.valueType!!.adapterString()) - } else { - addMember("adapter = %S", field.type!!.adapterString(field.useArray)) - } + ): AnnotationSpec = AnnotationSpec.builder(WireField::class) + .useSiteTarget(FIELD) + .addMember("tag = %L", field.tag) + .apply { + if (field.type!!.isMap) { + addMember("keyAdapter = %S", field.type!!.keyType!!.adapterString()) + addMember("adapter = %S", field.type!!.valueType!!.adapterString()) + } else { + addMember("adapter = %S", field.type!!.adapterString(field.useArray)) } - .apply { - val wireFieldLabel: WireField.Label? = - when (field.encodeMode!!) { - EncodeMode.REQUIRED -> WireField.Label.REQUIRED - EncodeMode.OMIT_IDENTITY -> { - // Wrapper types don't omit identity values on JSON as other proto3 messages would. - if (field.type!!.isWrapper) { - null - } else { - WireField.Label.OMIT_IDENTITY - } + } + .apply { + val wireFieldLabel: WireField.Label? = + when (field.encodeMode!!) { + EncodeMode.REQUIRED -> WireField.Label.REQUIRED + EncodeMode.OMIT_IDENTITY -> { + // Wrapper types don't omit identity values on JSON as other proto3 messages would. + if (field.type!!.isWrapper) { + null + } else { + WireField.Label.OMIT_IDENTITY } - EncodeMode.REPEATED -> WireField.Label.REPEATED - EncodeMode.PACKED -> WireField.Label.PACKED - EncodeMode.MAP, - EncodeMode.NULL_IF_ABSENT, - -> null } - if (wireFieldLabel != null) { - addMember("label = %T.%L", WireField.Label::class, wireFieldLabel) + EncodeMode.REPEATED -> WireField.Label.REPEATED + EncodeMode.PACKED -> WireField.Label.PACKED + EncodeMode.MAP, + EncodeMode.NULL_IF_ABSENT, + -> null } + if (wireFieldLabel != null) { + addMember("label = %T.%L", WireField.Label::class, wireFieldLabel) } - .apply { if (field.isRedacted) addMember("redacted = true") } - .apply { - val generatedName = nameAllocator(message)[field] - if (generatedName != field.name) { - addMember("declaredName = %S", field.name) - } + } + .apply { if (field.isRedacted) addMember("redacted = true") } + .apply { + val generatedName = nameAllocator(message)[field] + if (generatedName != field.name) { + addMember("declaredName = %S", field.name) } - .apply { - if (field.jsonName != field.name) { - addMember("jsonName = %S", field.jsonName!!) - } + } + .apply { + if (field.jsonName != field.name) { + addMember("jsonName = %S", field.jsonName!!) } - .apply { - if (field.isOneOf) { - val oneofName = message.oneOfs.first { it.fields.contains(field) }.name - addMember("oneofName = %S", oneofName) - } + } + .apply { + if (field.isOneOf) { + val oneofName = message.oneOfs.first { it.fields.contains(field) }.name + addMember("oneofName = %S", oneofName) } - .apply { - if (schemaIndex != null) { - addMember("schemaIndex = %L", schemaIndex) - } + } + .apply { + if (schemaIndex != null) { + addMember("schemaIndex = %L", schemaIndex) } - .build() - } + } + .build() private fun wireEnumConstantAnnotation(enum: EnumType, constant: EnumConstant): AnnotationSpec? { return AnnotationSpec.builder(WireEnumConstant::class) @@ -2274,12 +2264,10 @@ class KotlinGenerator private constructor( return null } - private fun Field.getAdapterName(nameDelimiter: Char = '.'): CodeBlock { - return if (type!!.isMap) { - CodeBlock.of("%N", "${name}Adapter") - } else { - type!!.getAdapterName(nameDelimiter) - } + private fun Field.getAdapterName(nameDelimiter: Char = '.'): CodeBlock = if (type!!.isMap) { + CodeBlock.of("%N", "${name}Adapter") + } else { + type!!.getAdapterName(nameDelimiter) } private fun ProtoType.getAdapterName(adapterFieldDelimiterName: Char = '.'): CodeBlock { @@ -3093,9 +3081,7 @@ class KotlinGenerator private constructor( return result } - private fun MessageType.boxOneOfs(): List { - return oneOfs.filter { it.fields.size >= boxOneOfsMinSize } - } + private fun MessageType.boxOneOfs(): List = oneOfs.filter { it.fields.size >= boxOneOfsMinSize } private fun MessageType.oneOfClassFor(oneOf: OneOf, nameAllocator: NameAllocator): TypeName { val oneOfClass = (this.typeName as ClassName) @@ -3285,13 +3271,9 @@ class KotlinGenerator private constructor( } private class ClassNameFactory : NameFactory { - override fun newName(packageName: String, simpleName: String): ClassName { - return ClassName(packageName, simpleName) - } + override fun newName(packageName: String, simpleName: String): ClassName = ClassName(packageName, simpleName) - override fun nestedName(enclosing: ClassName, simpleName: String): ClassName { - return enclosing.nestedClass(simpleName) - } + override fun nestedName(enclosing: ClassName, simpleName: String): ClassName = enclosing.nestedClass(simpleName) } private val Extend.annotationTargets: List @@ -3302,16 +3284,14 @@ class KotlinGenerator private constructor( else -> emptyList() } - internal fun String.sanitizeKdoc(): String { - return this - // Remove trailing whitespace on each line. - .replace("[^\\S\n]+\n".toRegex(), "\n") - .replace("\\s+$".toRegex(), "") - .replace("\\*/".toRegex(), "*/") - .replace("/\\*".toRegex(), "/*") - .replace("""[""", """\[""") - .replace("""]""", """\]""") - } + internal fun String.sanitizeKdoc(): String = this + // Remove trailing whitespace on each line. + .replace("[^\\S\n]+\n".toRegex(), "\n") + .replace("\\s+$".toRegex(), "") + .replace("\\*/".toRegex(), "*/") + .replace("/\\*".toRegex(), "/*") + .replace("""[""", """\[""") + .replace("""]""", """\]""") private const val DOUBLE_FULL_BLOCK = "\u2588\u2588" @@ -3323,11 +3303,10 @@ class KotlinGenerator private constructor( } } -private fun PropertySpec.Builder.jvmFieldIf(addJvmField: Boolean, jvmAnnotationPackage: String): PropertySpec.Builder = - if (addJvmField) { - this.addAnnotation( - ClassName(jvmAnnotationPackage, "JvmField"), - ) - } else { - this - } +private fun PropertySpec.Builder.jvmFieldIf(addJvmField: Boolean, jvmAnnotationPackage: String): PropertySpec.Builder = if (addJvmField) { + this.addAnnotation( + ClassName(jvmAnnotationPackage, "JvmField"), + ) +} else { + this +} diff --git a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt index dcef059ac9..88ef0c6c59 100644 --- a/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt +++ b/wire-kotlin-generator/src/test/java/com/squareup/wire/kotlin/KotlinWithProfilesGenerator.kt @@ -43,9 +43,7 @@ internal class KotlinWithProfilesGenerator(private val schema: Schema) { return this } - private fun profile(profileName: String?): Profile { - return if (profileName == null) Profile() else profiles["$profileName.wire"]!! - } + private fun profile(profileName: String?): Profile = if (profileName == null) Profile() else profiles["$profileName.wire"]!! fun generateKotlin( typeName: String, diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt index 4d271cf24f..b3938e9ae2 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/MoshiJsonIntegration.kt @@ -47,8 +47,7 @@ internal object MoshiJsonIntegration : JsonIntegration> return MapJsonAdapter(keyFormatter, valueAdapter).nullSafe() as JsonAdapter } - override fun structAdapter(framework: Moshi): JsonAdapter = - framework.adapter(Object::class.java).serializeNulls().nullSafe() + override fun structAdapter(framework: Moshi): JsonAdapter = framework.adapter(Object::class.java).serializeNulls().nullSafe() override fun formatterAdapter(jsonStringAdapter: JsonFormatter<*>): JsonAdapter { @Suppress("UNCHECKED_CAST") diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt index d3e2cce6f3..fb017be548 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/RedactingJsonAdapter.kt @@ -22,9 +22,7 @@ import com.squareup.moshi.JsonWriter fun JsonAdapter.redacting(): JsonAdapter { val delegate = this return object : JsonAdapter() { - override fun fromJson(reader: JsonReader): T? { - return delegate.fromJson(reader) - } + override fun fromJson(reader: JsonReader): T? = delegate.fromJson(reader) override fun toJson(writer: JsonWriter, value: T?) { var redactedTag = writer.tag(RedactedTag::class.java) diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt index c32a25dbe3..4d5c01f138 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/WireJsonAdapterFactory.kt @@ -70,9 +70,7 @@ class WireJsonAdapterFactory @JvmOverloads constructor( * Returns a new WireJsonAdapterFactory that can encode the messages for [adapter] if they're * used with [AnyMessage]. */ - fun plus(adapter: ProtoAdapter<*>): WireJsonAdapterFactory { - return plus(listOf(adapter)) - } + fun plus(adapter: ProtoAdapter<*>): WireJsonAdapterFactory = plus(listOf(adapter)) @Suppress("UNCHECKED_CAST") override fun create( diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt index 76b8b3a075..ecdc081c21 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/InteropChecker.kt @@ -86,11 +86,9 @@ class InteropChecker( } } - private fun JsonFormat.Parser.parse(json: String): Message { - return protocMessage.newBuilderForType() - .apply { merge(json, this) } - .build() - } + private fun JsonFormat.Parser.parse(json: String): Message = protocMessage.newBuilderForType() + .apply { merge(json, this) } + .build() private fun roundtripWireBytes(message: Any) { val adapter = ProtoAdapter.get(message::class.java) diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt index 6140bde701..4622a42035 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto2WireProtocCompatibilityTests.kt @@ -698,8 +698,6 @@ class Proto2WireProtocCompatibilityTests { .oneof_proto3_enum(EnumProto3J.A) .build() - private fun list(t: T): List { - return listOf(t, t) - } + private fun list(t: T): List = listOf(t, t) } } diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt index e863fcede7..6f48914c79 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/Proto3WireProtocCompatibilityTests.kt @@ -1385,13 +1385,9 @@ class Proto3WireProtocCompatibilityTests { .oneof_proto3_message(MessageProto3J.Builder().build()) .build() - private fun list(t: T): List { - return listOf(t, t) - } + private fun list(t: T): List = listOf(t, t) - private fun loadJson(fileName: String): String { - return File("../wire-tests/fixtures/shared/json", fileName) - .source().use { it.buffer().readUtf8() } - } + private fun loadJson(fileName: String): String = File("../wire-tests/fixtures/shared/json", fileName) + .source().use { it.buffer().readUtf8() } } } diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt index dfb13e18d3..a15b3f01b0 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocStructHelper.kt @@ -28,9 +28,7 @@ internal fun Map.toStruct(): Struct { return builder.build() } -internal fun emptyStruct(): Struct { - return Struct.newBuilder().build() -} +internal fun emptyStruct(): Struct = Struct.newBuilder().build() internal fun List<*>.toListValue(): ListValue { val builder = ListValue.newBuilder() @@ -40,18 +38,14 @@ internal fun List<*>.toListValue(): ListValue { return builder.build() } -internal fun emptyListValue(): ListValue { - return ListValue.newBuilder().build() -} +internal fun emptyListValue(): ListValue = ListValue.newBuilder().build() -internal fun Any?.toValue(): Value { - return when (this) { - null -> Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build() - is Double -> Value.newBuilder().setNumberValue(this).build() - is String -> Value.newBuilder().setStringValue(this).build() - is Boolean -> Value.newBuilder().setBoolValue(this).build() - is Map<*, *> -> Value.newBuilder().setStructValue((this as Map).toStruct()).build() - is List<*> -> Value.newBuilder().setListValue(toListValue()).build() - else -> throw IllegalArgumentException("unexpected struct value: $this") - } +internal fun Any?.toValue(): Value = when (this) { + null -> Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build() + is Double -> Value.newBuilder().setNumberValue(this).build() + is String -> Value.newBuilder().setStringValue(this).build() + is Boolean -> Value.newBuilder().setBoolValue(this).build() + is Map<*, *> -> Value.newBuilder().setStructValue((this as Map).toStruct()).build() + is List<*> -> Value.newBuilder().setListValue(toListValue()).build() + else -> throw IllegalArgumentException("unexpected struct value: $this") } diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt index 2e423d017d..3ef29977ae 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/ProtocWrappersHelper.kt @@ -27,29 +27,20 @@ import com.google.protobuf.UInt32Value import com.google.protobuf.UInt64Value import okio.ByteString -internal fun Double.toDoubleValue(): DoubleValue = - DoubleValue.newBuilder().setValue(this).build() +internal fun Double.toDoubleValue(): DoubleValue = DoubleValue.newBuilder().setValue(this).build() -internal fun Float.toFloatValue(): FloatValue = - FloatValue.newBuilder().setValue(this).build() +internal fun Float.toFloatValue(): FloatValue = FloatValue.newBuilder().setValue(this).build() -internal fun Long.toInt64Value(): Int64Value = - Int64Value.newBuilder().setValue(this).build() +internal fun Long.toInt64Value(): Int64Value = Int64Value.newBuilder().setValue(this).build() -internal fun Long.toUInt64Value(): UInt64Value = - UInt64Value.newBuilder().setValue(this).build() +internal fun Long.toUInt64Value(): UInt64Value = UInt64Value.newBuilder().setValue(this).build() -internal fun Int.toInt32Value(): Int32Value = - Int32Value.newBuilder().setValue(this).build() +internal fun Int.toInt32Value(): Int32Value = Int32Value.newBuilder().setValue(this).build() -internal fun Int.toUInt32Value(): UInt32Value = - UInt32Value.newBuilder().setValue(this).build() +internal fun Int.toUInt32Value(): UInt32Value = UInt32Value.newBuilder().setValue(this).build() -internal fun Boolean.toBoolValue(): BoolValue = - BoolValue.newBuilder().setValue(this).build() +internal fun Boolean.toBoolValue(): BoolValue = BoolValue.newBuilder().setValue(this).build() -internal fun String.toStringValue(): StringValue = - StringValue.newBuilder().setValue(this).build() +internal fun String.toStringValue(): StringValue = StringValue.newBuilder().setValue(this).build() -internal fun ByteString.toBytesValue(): BytesValue = - BytesValue.newBuilder().setValue(copyFrom(this.toByteArray())).build() +internal fun ByteString.toBytesValue(): BytesValue = BytesValue.newBuilder().setValue(copyFrom(this.toByteArray())).build() diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt index 17751a9794..d2633d61e0 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/StructTest.kt @@ -514,22 +514,20 @@ class StructTest { assertThat(allStructs.rep_struct).containsExactly(mapOf("a" to "b")) } - private fun Any?.isDeeplyUnmodifiable(): Boolean { - return when (this) { - null -> true - is String -> true - is Double -> true - is Int -> true - is Boolean -> true - is List<*> -> { - this.all { it.isDeeplyUnmodifiable() } && this.isUnmodifiable() - } - is Map<*, *> -> { - this.all { it.key.isDeeplyUnmodifiable() && it.value.isDeeplyUnmodifiable() } && - this.isUnmodifiable() - } - else -> false + private fun Any?.isDeeplyUnmodifiable(): Boolean = when (this) { + null -> true + is String -> true + is Double -> true + is Int -> true + is Boolean -> true + is List<*> -> { + this.all { it.isDeeplyUnmodifiable() } && this.isUnmodifiable() } + is Map<*, *> -> { + this.all { it.key.isDeeplyUnmodifiable() && it.value.isDeeplyUnmodifiable() } && + this.isUnmodifiable() + } + else -> false } @Suppress("LiftReturnOrAssignment") diff --git a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt index ed21574ef5..8dd5c26c19 100644 --- a/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt +++ b/wire-protoc-compatibility-tests/src/test/java/com/squareup/wire/UnwantedValueStripper.kt @@ -50,14 +50,12 @@ class UnwantedValueStripper( .build() } - fun stripOptionsAndDefaults(fieldDescriptorProto: FieldDescriptorProto): FieldDescriptorProto { - return fieldDescriptorProto.toBuilder() - .clearDefaultValue() - .apply { - if (clearJsonName) { - clearJsonName() - } + fun stripOptionsAndDefaults(fieldDescriptorProto: FieldDescriptorProto): FieldDescriptorProto = fieldDescriptorProto.toBuilder() + .clearDefaultValue() + .apply { + if (clearJsonName) { + clearJsonName() } - .build() - } + } + .build() } diff --git a/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto2InteropTest.kt b/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto2InteropTest.kt index 4673b22365..b43eee4e80 100644 --- a/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto2InteropTest.kt +++ b/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto2InteropTest.kt @@ -46,6 +46,7 @@ internal class GrpcurlProto2InteropTest { ).isEqualTo(expectedResponse) } + @Suppress("ktlint:standard:property-naming") val ECHO2_FILEDESCRIPTOR_RESPONSE = "Cg5sb2NhbGhvc3Q6OTA5MBIcCg5sb2NhbGhvc3Q6OTA5MCIKZWNobzIuRWNobyLxTwr5CgoRZWNobzIvZWNobzIucHJvdG8SBWVjaG8yGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvGhlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvIlsKDEhlbGxvUmVxdWVzdBIYCgdtZXNzYWdlGAEgAigJUgdtZXNzYWdlEjEKDG1vcmVfZGV0YWlscxgCIAEoCzIOLmVjaG8yLkRldGFpbHNSC21vcmVEZXRh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ZW50cxgEIAEoCVIQdHJhaWxpbmdDb21tZW50cxI6ChlsZWFkaW5nX2RldGFjaGVkX2NvbW1lbnRzGAYgAygJUhdsZWFkaW5nRGV0YWNoZWRDb21tZW50cyLRAQoRR2VuZXJhdGVkQ29kZUluZm8STQoKYW5ub3RhdGlvbhgBIAMoCzItLmdvb2dsZS5wcm90b2J1Zi5HZW5lcmF0ZWRDb2RlSW5mby5Bbm5vdGF0aW9uUgphbm5vdGF0aW9uGm0KCkFubm90YXRpb24SFgoEcGF0aBgBIAMoBUICEAFSBHBhdGgSHwoLc291cmNlX2ZpbGUYAiABKAlSCnNvdXJjZUZpbGUSFAoFYmVnaW4YAyABKAVSBWJlZ2luEhAKA2VuZBgEIAEoBVIDZW5kQn4KE2NvbS5nb29nbGUucHJvdG9idWZCEERlc2NyaXB0b3JQcm90b3NIAVotZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMvZGVzY3JpcHRvcnBi+AEBogIDR1BCqgIaR29vZ2xlLlByb3RvYnVmLlJlZmxlY3Rpb24=" @Test @@ -116,20 +117,18 @@ internal class GrpcurlProto2InteropTest { } } -private fun loadSchema(): Schema { - return SchemaLoader(FileSystem.SYSTEM) - .apply { - initRoots( - // TODO(juliaogris): Can we derive dependencies transitively? - sourcePath = listOf( - Location.get("src/main/resources", "grpc/reflection/v1alpha/reflection.proto"), - Location.get("src/test/proto", "echo2/echo2.proto"), - Location.get("src/test/proto", "google/api/annotations.proto"), - Location.get("src/test/proto", "google/api/http.proto"), - Location.get("src/test/proto", "google/protobuf/any.proto"), - ), - protoPath = listOf(), - ) - } - .loadSchema() -} +private fun loadSchema(): Schema = SchemaLoader(FileSystem.SYSTEM) + .apply { + initRoots( + // TODO(juliaogris): Can we derive dependencies transitively? + sourcePath = listOf( + Location.get("src/main/resources", "grpc/reflection/v1alpha/reflection.proto"), + Location.get("src/test/proto", "echo2/echo2.proto"), + Location.get("src/test/proto", "google/api/annotations.proto"), + Location.get("src/test/proto", "google/api/http.proto"), + Location.get("src/test/proto", "google/protobuf/any.proto"), + ), + protoPath = listOf(), + ) + } + .loadSchema() diff --git a/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto3InteropTest.kt b/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto3InteropTest.kt index 335266518a..56996902f3 100644 --- a/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto3InteropTest.kt +++ b/wire-reflector/src/test/kotlin/com/squareup/wire/reflector/GrpcurlProto3InteropTest.kt @@ -49,6 +49,7 @@ internal class GrpcurlProto3InteropTest { ).isEqualTo(expectedListResponse) } + @Suppress("ktlint:standard:property-naming") val ECHO3_FILEDESCRIPTOR_RESPONSE = "Cg5sb2NhbGhvc3Q6OTA5MBIcCg5sb2NhbGhvc3Q6OTA5MCIKZWNobzMuRWNobyKGUAqOCwoRZWNobzMvZWNobzMucHJvdG8SBWVjaG8zGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvGhlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvIlsKDEhlbGxvUmVxdWVzdBIYCgdtZXNzYWdlGAEgASgJUgdtZXNzYWdlEjEKDG1vcmVfZGV0YWlscxgCIAEoCzIOLmVjaG8zLkRldGFpbHNSC21vcmVEZXRhaWxzIjYKDUhlbGxvUmVzcG9uc2USJQoOcm9ib3RfcmVzcG9uc2UYASABKAlSDXJvYm90UmVzcG9uc2UiiwUKB0RldGFpbHMSPwoLbGFiZWxfY291bnQYASADKAsyHi5lY2hvMy5EZXRhaWxzLkxhYmVsQ291bnRFbnRyeVIKbGFiZWxDb3VudBIvCgpjb2xvcl90eXBlGAIgASgOMhAuZWNobzMuQ29sb3JUeXBlUgljb2xvclR5cGUSKwoDYW55GAMgASgLMhQuZ29vZ2xlLnByb3RvYnVmLkFueUgAUgNhbnmIAQESOQoNbm90aWZpY2F0aW9ucxgEIAMoCzITLmVjaG8zLk5vdGlmaWNhdGlvblINbm90aWZpY2F0a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mVnaW4YAyABKAVSBWJlZ2luEhAKA2VuZBgEIAEoBVIDZW5kQn4KE2NvbS5nb29nbGUucHJvdG9idWZCEERlc2NyaXB0b3JQcm90b3NIAVotZ29vZ2xlLmdvbGFuZy5vcmcvcHJvdG9idWYvdHlwZXMvZGVzY3JpcHRvcnBi+AEBogIDR1BCqgIaR29vZ2xlLlByb3RvYnVmLlJlZmxlY3Rpb24=" @Test @@ -97,6 +98,7 @@ internal class GrpcurlProto3InteropTest { .isEqualTo(unwantedValueStripper.stripOptionsAndDefaults(expectedResponse.fileDescriptors[0])) } + @Suppress("ktlint:standard:property-naming") val GOOGLE_API_RPC_RESPONSE = "Cg5sb2NhbGhvc3Q6OTA5MBIhCg5sb2NhbGhvc3Q6OTA5MCIPZ29vZ2xlLmFwaS5odHRwIo5DCqgCChxnb29nbGUvYXBpL2Fubm90YXRpb25zLnByb3RvEgpnb29nbGUuYXBpGhVnb29nbGUvYXBpL2h0dHAucHJvdG8aIGdvb2dsZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnByb3RvOksKBGh0dHASHi5nb29nbGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucxiwyrwiIAEoCzIULmdvb2dsZS5hcGkuSHR0cFJ1bGVSBGh0dHBCbgoOY29tLmdvb2dsZS5hcGlCEEFubm90YXRpb25zUHJvdG9QAVpBZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvYW5ub3RhdGlvbnM7YW5ub3RhdGlvbnOiAgRHQVBJYgZwcm90bzMKrAUKFWdvb2dsZS9hcGkvaHR0cC5wcm90bxIKZ29vZ2xlLmFwaSJ5CgRIdHRwEioKBXJ1bGVzGAEgAygLMhQuZ29vZ2xlLmFwaS5IdHRwUnVsZVIFcnVsZXMSRQofZnVsbHlfZGVjb2RlX3Jlc2VydmVkX2V4cGFuc2lvbhgCIAEoCFIcZnVsbHlEZWNvZGVSZXNlcnZlZEV4cGFuc2lvbiLaAgoISHR0cFJ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iAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVmbGVjdGlvbg==" @Test @@ -175,19 +177,17 @@ internal class GrpcurlProto3InteropTest { } } -private fun loadSchema(): Schema { - return SchemaLoader(FileSystem.SYSTEM) - .apply { - initRoots( - sourcePath = listOf( - Location.get("src/main/resources", "grpc/reflection/v1alpha/reflection.proto"), - Location.get("src/test/proto", "echo3/echo3.proto"), - Location.get("src/test/proto", "google/api/annotations.proto"), - Location.get("src/test/proto", "google/api/http.proto"), - Location.get("src/test/proto", "google/protobuf/any.proto"), - ), - protoPath = listOf(), - ) - } - .loadSchema() -} +private fun loadSchema(): Schema = SchemaLoader(FileSystem.SYSTEM) + .apply { + initRoots( + sourcePath = listOf( + Location.get("src/main/resources", "grpc/reflection/v1alpha/reflection.proto"), + Location.get("src/test/proto", "echo3/echo3.proto"), + Location.get("src/test/proto", "google/api/annotations.proto"), + Location.get("src/test/proto", "google/api/http.proto"), + Location.get("src/test/proto", "google/protobuf/any.proto"), + ), + protoPath = listOf(), + ) + } + .loadSchema() diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/AnyMessage.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/AnyMessage.kt index 6cd8e5065a..dc10e0c363 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/AnyMessage.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/AnyMessage.kt @@ -44,9 +44,7 @@ class AnyMessage( return adapter.decode(value) } - fun unpackOrNull(adapter: ProtoAdapter): T? { - return if (typeUrl == adapter.typeUrl) adapter.decode(value) else null - } + fun unpackOrNull(adapter: ProtoAdapter): T? = if (typeUrl == adapter.typeUrl) adapter.decode(value) else null @Deprecated( message = "Shouldn't be used in Kotlin", @@ -91,9 +89,8 @@ class AnyMessage( "type.googleapis.com/google.protobuf.Any", Syntax.PROTO_3, ) { - override fun encodedSize(value: AnyMessage): Int = - STRING.encodedSizeWithTag(1, value.typeUrl) + - BYTES.encodedSizeWithTag(2, value.value) + override fun encodedSize(value: AnyMessage): Int = STRING.encodedSizeWithTag(1, value.typeUrl) + + BYTES.encodedSizeWithTag(2, value.value) override fun encode(writer: ProtoWriter, value: AnyMessage) { STRING.encodeWithTag(writer, 1, value.typeUrl) @@ -132,8 +129,7 @@ class AnyMessage( } // TODO: this is a hazard. - override fun redact(value: AnyMessage) = - AnyMessage("square.github.io/wire/redacted", ByteString.EMPTY) + override fun redact(value: AnyMessage) = AnyMessage("square.github.io/wire/redacted", ByteString.EMPTY) } } } diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/EnumAdapter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/EnumAdapter.kt index 629c0a82ac..8a0544abca 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/EnumAdapter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/EnumAdapter.kt @@ -45,9 +45,7 @@ expect abstract class EnumAdapter protected constructor( } @Suppress("NOTHING_TO_INLINE") -internal inline fun commonEncodedSize(value: E): Int { - return ProtoWriter.varint32Size(value.value) -} +internal inline fun commonEncodedSize(value: E): Int = ProtoWriter.varint32Size(value.value) @Suppress("NOTHING_TO_INLINE") internal inline fun commonEncode(writer: ProtoWriter, value: E) { @@ -78,6 +76,4 @@ internal inline fun EnumAdapter.commonDecode( } @Suppress("NOTHING_TO_INLINE", "UNUSED_PARAMETER") -internal inline fun commonRedact(value: E): E { - throw UnsupportedOperationException() -} +internal inline fun commonRedact(value: E): E = throw UnsupportedOperationException() diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/FieldEncoding.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/FieldEncoding.kt index fda0910bf7..58d9cb7504 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/FieldEncoding.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/FieldEncoding.kt @@ -20,7 +20,11 @@ import kotlin.Throws import okio.IOException enum class FieldEncoding(internal val value: Int) { - VARINT(0), FIXED64(1), LENGTH_DELIMITED(2), FIXED32(5); + VARINT(0), + FIXED64(1), + LENGTH_DELIMITED(2), + FIXED32(5), + ; /** * Returns a Wire adapter that reads this field encoding without interpretation. For example, diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/OneOf.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/OneOf.kt index 78eaa2afc8..0aa5ebb603 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/OneOf.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/OneOf.kt @@ -127,9 +127,7 @@ data class OneOf, T>( return """${key.declaredName}=$valueAsString""" } - fun encodedSizeWithTag(): Int { - return key.adapter.encodedSizeWithTag(key.tag, value) - } + fun encodedSizeWithTag(): Int = key.adapter.encodedSizeWithTag(key.tag, value) fun encodeWithTag(writer: ProtoWriter) { key.adapter.encodeWithTag(writer, key.tag, value) diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoAdapter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoAdapter.kt index 38257194f5..806bb3e8e5 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoAdapter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoAdapter.kt @@ -349,19 +349,13 @@ internal inline fun ProtoAdapter.commonEncodeByteString(value: E): ByteSt } @Suppress("NOTHING_TO_INLINE") -internal inline fun ProtoAdapter.commonDecode(bytes: ByteArray): E { - return decode(ProtoReader32(bytes)) -} +internal inline fun ProtoAdapter.commonDecode(bytes: ByteArray): E = decode(ProtoReader32(bytes)) @Suppress("NOTHING_TO_INLINE") -internal inline fun ProtoAdapter.commonDecode(bytes: ByteString): E { - return decode(ProtoReader32(bytes)) -} +internal inline fun ProtoAdapter.commonDecode(bytes: ByteString): E = decode(ProtoReader32(bytes)) @Suppress("NOTHING_TO_INLINE") -internal inline fun ProtoAdapter.commonDecode(source: BufferedSource): E { - return decode(ProtoReader(source)) -} +internal inline fun ProtoAdapter.commonDecode(source: BufferedSource): E = decode(ProtoReader(source)) @Suppress("NOTHING_TO_INLINE") internal inline fun ProtoAdapter.commonTryDecode( @@ -431,9 +425,7 @@ internal class PackedProtoAdapter( return size } - override fun encodedSizeWithTag(tag: Int, value: List?): Int { - return if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) - } + override fun encodedSizeWithTag(tag: Int, value: List?): Int = if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) override fun encode(writer: ProtoWriter, value: List) { for (i in 0 until value.size) { @@ -455,9 +447,7 @@ internal class PackedProtoAdapter( } @Suppress("NOTHING_TO_INLINE") -internal inline fun ProtoAdapter.commonCreateRepeated(): ProtoAdapter> { - return RepeatedProtoAdapter(originalAdapter = this) -} +internal inline fun ProtoAdapter.commonCreateRepeated(): ProtoAdapter> = RepeatedProtoAdapter(originalAdapter = this) internal class RepeatedProtoAdapter( private val originalAdapter: ProtoAdapter, @@ -468,9 +458,7 @@ internal class RepeatedProtoAdapter( originalAdapter.syntax, listOf(), ) { - override fun encodedSize(value: List): Int { - throw UnsupportedOperationException("Repeated values can only be sized with a tag.") - } + override fun encodedSize(value: List): Int = throw UnsupportedOperationException("Repeated values can only be sized with a tag.") override fun encodedSizeWithTag(tag: Int, value: List?): Int { if (value == null) return 0 @@ -481,13 +469,9 @@ internal class RepeatedProtoAdapter( return size } - override fun encode(writer: ProtoWriter, value: List) { - throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - } + override fun encode(writer: ProtoWriter, value: List): Unit = throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - override fun encode(writer: ReverseProtoWriter, value: List) { - throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - } + override fun encode(writer: ReverseProtoWriter, value: List): Unit = throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") override fun encodeWithTag(writer: ProtoWriter, tag: Int, value: List?) { if (value == null) return @@ -539,9 +523,7 @@ internal class DoubleArrayProtoAdapter( return size } - override fun encodedSizeWithTag(tag: Int, value: DoubleArray?): Int { - return if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) - } + override fun encodedSizeWithTag(tag: Int, value: DoubleArray?): Int = if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) override fun encode(writer: ProtoWriter, value: DoubleArray) { for (i in 0 until value.size) { @@ -555,11 +537,9 @@ internal class DoubleArrayProtoAdapter( } } - override fun decode(reader: ProtoReader): DoubleArray = - doubleArrayOf(Double.fromBits(reader.readFixed64())) + override fun decode(reader: ProtoReader): DoubleArray = doubleArrayOf(Double.fromBits(reader.readFixed64())) - override fun decode(reader: ProtoReader32): DoubleArray = - doubleArrayOf(Double.fromBits(reader.readFixed64())) + override fun decode(reader: ProtoReader32): DoubleArray = doubleArrayOf(Double.fromBits(reader.readFixed64())) override fun redact(value: DoubleArray): DoubleArray = doubleArrayOf() } @@ -593,9 +573,7 @@ internal class LongArrayProtoAdapter( return size } - override fun encodedSizeWithTag(tag: Int, value: LongArray?): Int { - return if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) - } + override fun encodedSizeWithTag(tag: Int, value: LongArray?): Int = if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) override fun encode(writer: ProtoWriter, value: LongArray) { for (i in 0 until value.size) { @@ -645,9 +623,7 @@ internal class FloatArrayProtoAdapter( return size } - override fun encodedSizeWithTag(tag: Int, value: FloatArray?): Int { - return if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) - } + override fun encodedSizeWithTag(tag: Int, value: FloatArray?): Int = if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) override fun encode(writer: ProtoWriter, value: FloatArray) { for (i in 0 until value.size) { @@ -661,11 +637,9 @@ internal class FloatArrayProtoAdapter( } } - override fun decode(reader: ProtoReader): FloatArray = - floatArrayOf(Float.fromBits(reader.readFixed32())) + override fun decode(reader: ProtoReader): FloatArray = floatArrayOf(Float.fromBits(reader.readFixed32())) - override fun decode(reader: ProtoReader32): FloatArray = - floatArrayOf(Float.fromBits(reader.readFixed32())) + override fun decode(reader: ProtoReader32): FloatArray = floatArrayOf(Float.fromBits(reader.readFixed32())) override fun redact(value: FloatArray): FloatArray = floatArrayOf() } @@ -699,9 +673,7 @@ internal class IntArrayProtoAdapter( return size } - override fun encodedSizeWithTag(tag: Int, value: IntArray?): Int { - return if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) - } + override fun encodedSizeWithTag(tag: Int, value: IntArray?): Int = if (value == null || value.isEmpty()) 0 else super.encodedSizeWithTag(tag, value) override fun encode(writer: ProtoWriter, value: IntArray) { for (i in 0 until value.size) { @@ -734,9 +706,7 @@ internal class MapProtoAdapter internal constructor( ) { private val entryAdapter = MapEntryProtoAdapter(keyAdapter, valueAdapter) - override fun encodedSize(value: Map): Int { - throw UnsupportedOperationException("Repeated values can only be sized with a tag.") - } + override fun encodedSize(value: Map): Int = throw UnsupportedOperationException("Repeated values can only be sized with a tag.") override fun encodedSizeWithTag(tag: Int, value: Map?): Int { if (value == null) return 0 @@ -747,13 +717,9 @@ internal class MapProtoAdapter internal constructor( return size } - override fun encode(writer: ProtoWriter, value: Map) { - throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - } + override fun encode(writer: ProtoWriter, value: Map): Unit = throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - override fun encode(writer: ReverseProtoWriter, value: Map) { - throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") - } + override fun encode(writer: ReverseProtoWriter, value: Map): Unit = throw UnsupportedOperationException("Repeated values can only be encoded with a tag.") override fun encodeWithTag(writer: ProtoWriter, tag: Int, value: Map?) { if (value == null) return @@ -824,10 +790,8 @@ private class MapEntryProtoAdapter internal constructor( valueAdapter.syntax, ) { - override fun encodedSize(value: Map.Entry): Int { - return keyAdapter.encodedSizeWithTag(1, value.key) + - valueAdapter.encodedSizeWithTag(2, value.value) - } + override fun encodedSize(value: Map.Entry): Int = keyAdapter.encodedSizeWithTag(1, value.key) + + valueAdapter.encodedSizeWithTag(2, value.value) override fun encode(writer: ProtoWriter, value: Map.Entry) { keyAdapter.encodeWithTag(writer, 1, value.key) @@ -839,13 +803,9 @@ private class MapEntryProtoAdapter internal constructor( keyAdapter.encodeWithTag(writer, 1, value.key) } - override fun decode(reader: ProtoReader): Map.Entry { - throw UnsupportedOperationException() - } + override fun decode(reader: ProtoReader): Map.Entry = throw UnsupportedOperationException() - override fun redact(value: Map.Entry): Map.Entry { - throw UnsupportedOperationException() - } + override fun redact(value: Map.Entry): Map.Entry = throw UnsupportedOperationException() } private const val FIXED_BOOL_SIZE = 1 @@ -856,9 +816,7 @@ private const val FIXED_64_SIZE = 8 internal inline fun commonNewMapAdapter( keyAdapter: ProtoAdapter, valueAdapter: ProtoAdapter, -): ProtoAdapter> { - return MapProtoAdapter(keyAdapter, valueAdapter) -} +): ProtoAdapter> = MapProtoAdapter(keyAdapter, valueAdapter) internal fun commonBool(): ProtoAdapter = object : ProtoAdapter( VARINT, @@ -1090,13 +1048,14 @@ internal fun commonFixed64(): ProtoAdapter = object : ProtoAdapter( override fun redact(value: Long): Long = throw UnsupportedOperationException() } -internal class FloatProtoAdapter : ProtoAdapter( - FieldEncoding.FIXED32, - Float::class, - null, - Syntax.PROTO_2, - 0.0f, -) { +internal class FloatProtoAdapter : + ProtoAdapter( + FieldEncoding.FIXED32, + Float::class, + null, + Syntax.PROTO_2, + 0.0f, + ) { override fun encode(writer: ProtoWriter, value: Float) { writer.writeFixed32(value.toBits()) } @@ -1105,13 +1064,9 @@ internal class FloatProtoAdapter : ProtoAdapter( writer.writeFixed32(value.toBits()) } - override fun decode(reader: ProtoReader): Float { - return Float.fromBits(reader.readFixed32()) - } + override fun decode(reader: ProtoReader): Float = Float.fromBits(reader.readFixed32()) - override fun decode(reader: ProtoReader32): Float { - return Float.fromBits(reader.readFixed32()) - } + override fun decode(reader: ProtoReader32): Float = Float.fromBits(reader.readFixed32()) override fun encodedSize(value: Float): Int = FIXED_32_SIZE @@ -1121,13 +1076,14 @@ internal class FloatProtoAdapter : ProtoAdapter( internal fun commonSfixed64() = commonFixed64() internal fun commonFloat(): FloatProtoAdapter = FloatProtoAdapter() -internal class DoubleProtoAdapter : ProtoAdapter( - FieldEncoding.FIXED64, - Double::class, - null, - Syntax.PROTO_2, - 0.0, -) { +internal class DoubleProtoAdapter : + ProtoAdapter( + FieldEncoding.FIXED64, + Double::class, + null, + Syntax.PROTO_2, + 0.0, + ) { override fun encodedSize(value: Double): Int = FIXED_64_SIZE override fun encode(writer: ProtoWriter, value: Double) { diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoReader32AsProtoReader.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoReader32AsProtoReader.kt index 25f26a1dea..843fb6510c 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoReader32AsProtoReader.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoReader32AsProtoReader.kt @@ -30,8 +30,7 @@ internal class ProtoReader32AsProtoReader( ) : ProtoReader(Buffer()) { override fun beginMessage() = delegate.beginMessage().toLong() - override fun endMessageAndGetUnknownFields(token: Long) = - delegate.endMessageAndGetUnknownFields(token.toInt()) + override fun endMessageAndGetUnknownFields(token: Long) = delegate.endMessageAndGetUnknownFields(token.toInt()) override fun nextLengthDelimited() = delegate.nextLengthDelimited() diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoWriter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoWriter.kt index 74c0aad164..2fba2ff56f 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoWriter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ProtoWriter.kt @@ -128,9 +128,7 @@ class ProtoWriter(private val sink: BufferedSink) { companion object { /** Makes a tag value given a field number and wire type. */ - internal fun makeTag(fieldNumber: Int, fieldEncoding: FieldEncoding): Int { - return (fieldNumber shl ProtoReader.TAG_FIELD_ENCODING_BITS) or fieldEncoding.value - } + internal fun makeTag(fieldNumber: Int, fieldEncoding: FieldEncoding): Int = (fieldNumber shl ProtoReader.TAG_FIELD_ENCODING_BITS) or fieldEncoding.value /** Compute the number of bytes that would be needed to encode a tag. */ internal fun tagSize(tag: Int): Int = varint32Size(makeTag(tag, FieldEncoding.VARINT)) @@ -139,13 +137,11 @@ class ProtoWriter(private val sink: BufferedSink) { * Computes the number of bytes that would be needed to encode a signed variable-length integer * of up to 32 bits. */ - internal fun int32Size(value: Int): Int { - return if (value >= 0) { - varint32Size(value) - } else { - // Must sign-extend. - 10 - } + internal fun int32Size(value: Int): Int = if (value >= 0) { + varint32Size(value) + } else { + // Must sign-extend. + 10 } /** diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt index eff10c6808..fb9483d2ba 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/ReverseProtoWriter.kt @@ -155,8 +155,8 @@ class ReverseProtoWriter { // Emit a 11-bit character with 2 bytes. require(2) // @formatter:off - array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx - array[--arrayLimit] = (c shr 6 or 0xc0).toByte() // 110xxxxx + array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx + array[--arrayLimit] = (c shr 6 or 0xc0).toByte() // 110xxxxx // @formatter:on } @@ -164,9 +164,9 @@ class ReverseProtoWriter { // Emit a 16-bit character with 3 bytes. require(3) // @formatter:off - array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx - array[--arrayLimit] = (c shr 6 and 0x3f or 0x80).toByte() // 10xxxxxx - array[--arrayLimit] = (c shr 12 or 0xe0).toByte() // 1110xxxx + array[--arrayLimit] = (c and 0x3f or 0x80).toByte() // 10xxxxxx + array[--arrayLimit] = (c shr 6 and 0x3f or 0x80).toByte() // 10xxxxxx + array[--arrayLimit] = (c shr 12 or 0xe0).toByte() // 1110xxxx // @formatter:on } @@ -188,10 +188,10 @@ class ReverseProtoWriter { // Emit a 21-bit character with 4 bytes. require(4) // @formatter:off - array[--arrayLimit] = (codePoint and 0x3f or 0x80).toByte() // 10yyyyyy - array[--arrayLimit] = (codePoint shr 6 and 0x3f or 0x80).toByte() // 10xxyyyy + array[--arrayLimit] = (codePoint and 0x3f or 0x80).toByte() // 10yyyyyy + array[--arrayLimit] = (codePoint shr 6 and 0x3f or 0x80).toByte() // 10xxyyyy array[--arrayLimit] = (codePoint shr 12 and 0x3f or 0x80).toByte() // 10xxxxxx - array[--arrayLimit] = (codePoint shr 18 or 0xf0).toByte() // 11110xxx + array[--arrayLimit] = (codePoint shr 18 or 0xf0).toByte() // 11110xxx // @formatter:on } } @@ -255,10 +255,10 @@ class ReverseProtoWriter { arrayLimit -= 4 var offset = arrayLimit // @formatter:off - array[offset++] = (value and 0xff).toByte() - array[offset++] = (value ushr 8 and 0xff).toByte() + array[offset++] = (value and 0xff).toByte() + array[offset++] = (value ushr 8 and 0xff).toByte() array[offset++] = (value ushr 16 and 0xff).toByte() - array[offset ] = (value ushr 24 and 0xff).toByte() + array[offset ] = (value ushr 24 and 0xff).toByte() // @formatter:on } @@ -268,14 +268,14 @@ class ReverseProtoWriter { arrayLimit -= 8 var offset = arrayLimit // @formatter:off - array[offset++] = (value and 0xffL).toByte() - array[offset++] = (value ushr 8 and 0xffL).toByte() + array[offset++] = (value and 0xffL).toByte() + array[offset++] = (value ushr 8 and 0xffL).toByte() array[offset++] = (value ushr 16 and 0xffL).toByte() array[offset++] = (value ushr 24 and 0xffL).toByte() array[offset++] = (value ushr 32 and 0xffL).toByte() array[offset++] = (value ushr 40 and 0xffL).toByte() array[offset++] = (value ushr 48 and 0xffL).toByte() - array[offset ] = (value ushr 56 and 0xffL).toByte() + array[offset ] = (value ushr 56 and 0xffL).toByte() // @formatter:on } diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/ImmutableList.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/ImmutableList.kt index 3f8adb6947..cd178d59d0 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/ImmutableList.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/ImmutableList.kt @@ -15,7 +15,10 @@ */ package com.squareup.wire.internal -internal class ImmutableList(list: List) : AbstractList(), RandomAccess, Serializable { +internal class ImmutableList(list: List) : + AbstractList(), + RandomAccess, + Serializable { private val list = ArrayList(list) override val size: Int diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/Internal.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/Internal.kt index 0aa926860a..52e1f04fe1 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/Internal.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/Internal.kt @@ -43,12 +43,10 @@ fun newMutableMap(): MutableMap = LinkedHashMap() ) fun copyOf(@Suppress("UNUSED_PARAMETER") name: String, list: List?): MutableList = copyOf(list!!) -fun copyOf(list: List): MutableList { - return if (list === emptyList() || list is ImmutableList<*>) { - MutableOnWriteList(list) - } else { - ArrayList(list) - } +fun copyOf(list: List): MutableList = if (list === emptyList() || list is ImmutableList<*>) { + MutableOnWriteList(list) +} else { + ArrayList(list) } @Deprecated( @@ -98,34 +96,32 @@ fun immutableCopyOfMapWithStructValues(name: String, map: Map): Map } /** Confirms [value] is a struct and returns an immutable copy. */ -fun immutableCopyOfStruct(name: String, value: T): T { - return when (value) { - null -> value - is Boolean -> value - is Double -> value - is String -> value - is List<*> -> { - val copy = mutableListOf() - for (element in value) { - copy += immutableCopyOfStruct(name, element) - } - @Suppress("UNCHECKED_CAST") - copy.toUnmodifiableList() as T - } - is Map<*, *> -> { - val copy = mutableMapOf() - for ((k, v) in value) { - copy[immutableCopyOfStruct(name, k)] = immutableCopyOfStruct(name, v) - } - @Suppress("UNCHECKED_CAST") - copy.toUnmodifiableMap() as T +fun immutableCopyOfStruct(name: String, value: T): T = when (value) { + null -> value + is Boolean -> value + is Double -> value + is String -> value + is List<*> -> { + val copy = mutableListOf() + for (element in value) { + copy += immutableCopyOfStruct(name, element) } - else -> { - throw IllegalArgumentException( - "struct value $name must be a JSON type " + - "(null, Boolean, Double, String, List, or Map) but was ${value.typeName}: $value", - ) + @Suppress("UNCHECKED_CAST") + copy.toUnmodifiableList() as T + } + is Map<*, *> -> { + val copy = mutableMapOf() + for ((k, v) in value) { + copy[immutableCopyOfStruct(name, k)] = immutableCopyOfStruct(name, v) } + @Suppress("UNCHECKED_CAST") + copy.toUnmodifiableMap() as T + } + else -> { + throw IllegalArgumentException( + "struct value $name must be a JSON type " + + "(null, Boolean, Double, String, List, or Map) but was ${value.typeName}: $value", + ) } } @@ -136,9 +132,7 @@ private val Any.typeName fun List.redactElements(adapter: ProtoAdapter): List = map(adapter::redact) @JvmName("-redactElements") // Hide from Java -fun Map.redactElements(adapter: ProtoAdapter): Map { - return mapValues { (_, value) -> adapter.redact(value) } -} +fun Map.redactElements(adapter: ProtoAdapter): Map = mapValues { (_, value) -> adapter.redact(value) } @Suppress("SuspiciousEqualsCombination") fun equals(a: Any?, b: Any?): Boolean = a === b || (a != null && a == b) @@ -189,9 +183,7 @@ fun checkElementsNotNull(map: Map<*, *>) { fun countNonNull(a: Any?, b: Any?): Int = (if (a != null) 1 else 0) + (if (b != null) 1 else 0) /** Returns the number of non-null values in `a, b, c`. */ -fun countNonNull(a: Any?, b: Any?, c: Any?): Int { - return (if (a != null) 1 else 0) + (if (b != null) 1 else 0) + (if (c != null) 1 else 0) -} +fun countNonNull(a: Any?, b: Any?, c: Any?): Int = (if (a != null) 1 else 0) + (if (b != null) 1 else 0) + (if (c != null) 1 else 0) /** Returns the number of non-null values in `a, b, c, d, rest`. */ fun countNonNull(a: Any?, b: Any?, c: Any?, d: Any?, vararg rest: Any?): Int { @@ -209,35 +201,25 @@ fun countNonNull(a: Any?, b: Any?, c: Any?, d: Any?, vararg rest: Any?): Int { private const val ESCAPED_CHARS = ",[]{}\\" /** Return a string where `,[]{}\` are escaped with a `\`. */ -fun sanitize(value: String): String { - return buildString(value.length) { - value.forEach { char -> - if (char in ESCAPED_CHARS) append('\\') - append(char) - } +fun sanitize(value: String): String = buildString(value.length) { + value.forEach { char -> + if (char in ESCAPED_CHARS) append('\\') + append(char) } } /** Return a string where `,[]{}\` are escaped with a `\`. */ -fun sanitize(values: List): String { - return values.joinToString(prefix = "[", postfix = "]", transform = ::sanitize) -} +fun sanitize(values: List): String = values.joinToString(prefix = "[", postfix = "]", transform = ::sanitize) -fun boxedOneOfClassName(oneOfName: String): String { - return oneOfName.replaceFirstChar(Char::titlecase) -} +fun boxedOneOfClassName(oneOfName: String): String = oneOfName.replaceFirstChar(Char::titlecase) /** * Maps [oneOfName] and [fieldName] to the companion object key representing a boxed oneof field. */ -fun boxedOneOfKeyFieldName(oneOfName: String, fieldName: String): String { - return (oneOfName + "_" + fieldName).uppercase() -} +fun boxedOneOfKeyFieldName(oneOfName: String, fieldName: String): String = (oneOfName + "_" + fieldName).uppercase() /** Maps [oneOfName] to the companion object field of type `Set` containing the eligible keys. */ -fun boxedOneOfKeysFieldName(oneOfName: String): String { - return "${oneOfName}_keys".uppercase() -} +fun boxedOneOfKeysFieldName(oneOfName: String): String = "${oneOfName}_keys".uppercase() fun encodeArray_int32(array: IntArray, writer: ReverseProtoWriter, tag: Int) { if (array.isNotEmpty()) { @@ -283,9 +265,7 @@ fun encodeArray_fixed32(array: IntArray, writer: ReverseProtoWriter, tag: Int) { } } -fun encodeArray_sfixed32(array: IntArray, writer: ReverseProtoWriter, tag: Int) { - return encodeArray_fixed32(array, writer, tag) -} +fun encodeArray_sfixed32(array: IntArray, writer: ReverseProtoWriter, tag: Int) = encodeArray_fixed32(array, writer, tag) fun encodeArray_int64(array: LongArray, writer: ReverseProtoWriter, tag: Int) { if (array.isNotEmpty()) { @@ -298,8 +278,7 @@ fun encodeArray_int64(array: LongArray, writer: ReverseProtoWriter, tag: Int) { } } -fun encodeArray_uint64(array: LongArray, writer: ReverseProtoWriter, tag: Int) = - encodeArray_int64(array, writer, tag) +fun encodeArray_uint64(array: LongArray, writer: ReverseProtoWriter, tag: Int) = encodeArray_int64(array, writer, tag) fun encodeArray_sint64(array: LongArray, writer: ReverseProtoWriter, tag: Int) { if (array.isNotEmpty()) { @@ -323,8 +302,7 @@ fun encodeArray_fixed64(array: LongArray, writer: ReverseProtoWriter, tag: Int) } } -fun encodeArray_sfixed64(array: LongArray, writer: ReverseProtoWriter, tag: Int) = - encodeArray_fixed64(array, writer, tag) +fun encodeArray_sfixed64(array: LongArray, writer: ReverseProtoWriter, tag: Int) = encodeArray_fixed64(array, writer, tag) fun encodeArray_float(array: FloatArray, writer: ReverseProtoWriter, tag: Int) { if (array.isNotEmpty()) { diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MutableOnWriteList.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MutableOnWriteList.kt index 5cfe469123..3a9e3c7b07 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MutableOnWriteList.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/MutableOnWriteList.kt @@ -18,7 +18,9 @@ package com.squareup.wire.internal /** A wrapper around an empty/immutable list which only switches to mutable on first mutation. */ internal class MutableOnWriteList( private val immutableList: List, -) : AbstractMutableList(), RandomAccess, Serializable { +) : AbstractMutableList(), + RandomAccess, + Serializable { internal var mutableList: List = immutableList override fun get(index: Int): T = mutableList[index] diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/RuntimeMessageAdapter.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/RuntimeMessageAdapter.kt index f4a4fe76a1..4c967d9a2c 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/RuntimeMessageAdapter.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/RuntimeMessageAdapter.kt @@ -141,9 +141,7 @@ class RuntimeMessageAdapter( return binding.build(builder) } - override fun equals(other: Any?): Boolean { - return other is RuntimeMessageAdapter<*, *> && other.messageType == messageType - } + override fun equals(other: Any?): Boolean = other is RuntimeMessageAdapter<*, *> && other.messageType == messageType override fun hashCode(): Int = messageType.hashCode() diff --git a/wire-runtime/src/commonTest/kotlin/com/squareup/wire/ReverseProtoWriterTest.kt b/wire-runtime/src/commonTest/kotlin/com/squareup/wire/ReverseProtoWriterTest.kt index 866b6c8c26..adf7b065fa 100644 --- a/wire-runtime/src/commonTest/kotlin/com/squareup/wire/ReverseProtoWriterTest.kt +++ b/wire-runtime/src/commonTest/kotlin/com/squareup/wire/ReverseProtoWriterTest.kt @@ -211,10 +211,8 @@ class ReverseProtoWriterTest { ) { override fun redact(value: Person) = error("unexpected call") - public override fun encodedSize(`value`: Person): Int { - return STRING.encodedSizeWithTag(1, value.name) + - INT32.encodedSizeWithTag(2, value.birthYear) - } + public override fun encodedSize(`value`: Person): Int = STRING.encodedSizeWithTag(1, value.name) + + INT32.encodedSizeWithTag(2, value.birthYear) public override fun encode(writer: ProtoWriter, `value`: Person) { STRING.encodeWithTag(writer, 1, value.name) @@ -251,10 +249,8 @@ class ReverseProtoWriterTest { ) { override fun redact(value: Task) = error("unexpected call") - public override fun encodedSize(`value`: Task): Int { - return STRING.encodedSizeWithTag(1, value.description) + - Person.ADAPTER.encodedSizeWithTag(2, value.assignee) - } + public override fun encodedSize(`value`: Task): Int = STRING.encodedSizeWithTag(1, value.description) + + Person.ADAPTER.encodedSizeWithTag(2, value.assignee) override fun encode(writer: ProtoWriter, value: Task) { STRING.encodeWithTag(writer, 1, value.description) diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/AndroidMessage.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/AndroidMessage.kt index 6d6d333fa7..738d18113c 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/AndroidMessage.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/AndroidMessage.kt @@ -24,7 +24,8 @@ import okio.ByteString abstract class AndroidMessage, B : Message.Builder> protected constructor( adapter: ProtoAdapter, unknownFields: ByteString, -) : Message(adapter, unknownFields), Parcelable { +) : Message(adapter, unknownFields), + Parcelable { override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeByteArray(encode()) @@ -38,14 +39,11 @@ abstract class AndroidMessage, B : Message.Builder> prot override fun createFromParcel(input: Parcel): M = adapter.decode(input.createByteArray()) @Suppress("UNCHECKED_CAST") - override fun newArray(size: Int): Array = - newInstance(adapter.type?.javaObjectType, size) as Array + override fun newArray(size: Int): Array = newInstance(adapter.type?.javaObjectType, size) as Array } companion object { /** Creates a new [Parcelable.Creator] using `adapter` for serialization. */ - @JvmStatic fun newCreator(adapter: ProtoAdapter): Parcelable.Creator { - return ProtoAdapterCreator(adapter) - } + @JvmStatic fun newCreator(adapter: ProtoAdapter): Parcelable.Creator = ProtoAdapterCreator(adapter) } } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Duration.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Duration.kt index 55eb031187..13b572ee5d 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Duration.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Duration.kt @@ -18,6 +18,4 @@ package com.squareup.wire actual typealias Duration = java.time.Duration @Suppress("NOTHING_TO_INLINE") -actual inline fun durationOfSeconds(seconds: Long, nano: Long): Duration { - return Duration.ofSeconds(seconds, nano) -} +actual inline fun durationOfSeconds(seconds: Long, nano: Long): Duration = Duration.ofSeconds(seconds, nano) diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Instant.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Instant.kt index eea4b83e7d..5eca083c97 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Instant.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/Instant.kt @@ -18,6 +18,4 @@ package com.squareup.wire actual typealias Instant = java.time.Instant @Suppress("NOTHING_TO_INLINE") -actual inline fun ofEpochSecond(epochSecond: Long, nano: Long): Instant { - return Instant.ofEpochSecond(epochSecond, nano) -} +actual inline fun ofEpochSecond(epochSecond: Long, nano: Long): Instant = Instant.ofEpochSecond(epochSecond, nano) diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/KotlinConstructorBuilder.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/KotlinConstructorBuilder.kt index 6d424912cf..232c05151e 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/KotlinConstructorBuilder.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/KotlinConstructorBuilder.kt @@ -61,20 +61,18 @@ internal class KotlinConstructorBuilder, B : Message.Builder() - } else if (field.label.isRepeated) { - repeatedFieldValueMap[field.tag]?.second ?: listOf() + fun get(field: WireField): Any? = if (field.isMap) { + mapFieldKeyValueMap[field.tag]?.second ?: mapOf() + } else if (field.label.isRepeated) { + repeatedFieldValueMap[field.tag]?.second ?: listOf() + } else { + val value = fieldValueMap[field.tag]?.second + // Proto3 singular fields have non-nullable types with default parameters, we need to pass + // the identity value to please the constructor. + if (value == null && field.label == WireField.Label.OMIT_IDENTITY) { + ProtoAdapter.get(field.adapter).identity } else { - val value = fieldValueMap[field.tag]?.second - // Proto3 singular fields have non-nullable types with default parameters, we need to pass - // the identity value to please the constructor. - if (value == null && field.label == WireField.Label.OMIT_IDENTITY) { - ProtoAdapter.get(field.adapter).identity - } else { - value - } + value } } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt index e45fb86cc3..815a641653 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt @@ -97,9 +97,7 @@ actual abstract class ProtoAdapter actual constructor( actual abstract fun encodedSize(value: E): Int - actual open fun encodedSizeWithTag(tag: Int, value: E?): Int { - return commonEncodedSizeWithTag(tag, value) - } + actual open fun encodedSizeWithTag(tag: Int, value: E?): Int = commonEncodedSizeWithTag(tag, value) @Throws(IOException::class) actual abstract fun encode(writer: ProtoWriter, value: E) @@ -124,13 +122,9 @@ actual abstract class ProtoAdapter actual constructor( commonEncode(sink, value) } - actual fun encode(value: E): ByteArray { - return commonEncode(value) - } + actual fun encode(value: E): ByteArray = commonEncode(value) - actual fun encodeByteString(value: E): ByteString { - return commonEncodeByteString(value) - } + actual fun encodeByteString(value: E): ByteString = commonEncodeByteString(value) @Throws(IOException::class) fun encode(stream: OutputStream, value: E) { @@ -144,45 +138,29 @@ actual abstract class ProtoAdapter actual constructor( /** Read a non-null value from `reader`. */ @Throws(IOException::class) - actual open fun decode(reader: ProtoReader32): E { - return decode(reader.asProtoReader()) - } + actual open fun decode(reader: ProtoReader32): E = decode(reader.asProtoReader()) @Throws(IOException::class) - actual fun decode(bytes: ByteArray): E { - return commonDecode(bytes) - } + actual fun decode(bytes: ByteArray): E = commonDecode(bytes) @Throws(IOException::class) - actual fun decode(bytes: ByteString): E { - return commonDecode(bytes) - } + actual fun decode(bytes: ByteString): E = commonDecode(bytes) @Throws(IOException::class) - actual fun decode(source: BufferedSource): E { - return commonDecode(source) - } + actual fun decode(source: BufferedSource): E = commonDecode(source) @Throws(IOException::class) - actual fun tryDecode(reader: ProtoReader, destination: MutableList) { - return commonTryDecode(reader, destination) - } + actual fun tryDecode(reader: ProtoReader, destination: MutableList) = commonTryDecode(reader, destination) @Throws(IOException::class) - actual fun tryDecode(reader: ProtoReader32, destination: MutableList) { - return commonTryDecode(reader, destination) - } + actual fun tryDecode(reader: ProtoReader32, destination: MutableList) = commonTryDecode(reader, destination) @Throws(IOException::class) fun decode(stream: InputStream): E = decode(stream.source().buffer()) - actual open fun toString(value: E): String { - return commonToString(value) - } + actual open fun toString(value: E): String = commonToString(value) - internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> { - return commonWithLabel(label) - } + internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> = commonWithLabel(label) actual fun asPacked(): ProtoAdapter> { require(fieldEncoding != FieldEncoding.LENGTH_DELIMITED) { @@ -193,11 +171,9 @@ actual abstract class ProtoAdapter actual constructor( ) } - actual fun asRepeated(): ProtoAdapter> { - return repeatedAdapter ?: throw UnsupportedOperationException( - "Can't create a repeated adapter from a repeated or packed adapter.", - ) - } + actual fun asRepeated(): ProtoAdapter> = repeatedAdapter ?: throw UnsupportedOperationException( + "Can't create a repeated adapter from a repeated or packed adapter.", + ) internal val isStruct: Boolean get() = this == STRUCT_MAP || this == STRUCT_LIST || this == STRUCT_VALUE || this == STRUCT_NULL @@ -213,33 +189,25 @@ actual abstract class ProtoAdapter actual constructor( @JvmStatic actual fun newMapAdapter( keyAdapter: ProtoAdapter, valueAdapter: ProtoAdapter, - ): ProtoAdapter> { - return commonNewMapAdapter(keyAdapter, valueAdapter) - } + ): ProtoAdapter> = commonNewMapAdapter(keyAdapter, valueAdapter) // Obsolete; for Java classes generated before typeUrl and syntax were added. @JvmStatic fun , B : Message.Builder> newMessageAdapter( type: Class, - ): ProtoAdapter { - return createRuntimeMessageAdapter(type, null, Syntax.PROTO_2) - } + ): ProtoAdapter = createRuntimeMessageAdapter(type, null, Syntax.PROTO_2) // Obsolete; for Java classes generated before typeUrl and syntax were added. @JvmStatic fun , B : Message.Builder> newMessageAdapter( type: Class, typeUrl: String, - ): ProtoAdapter { - return createRuntimeMessageAdapter(type, typeUrl, Syntax.PROTO_2) - } + ): ProtoAdapter = createRuntimeMessageAdapter(type, typeUrl, Syntax.PROTO_2) // Obsolete; for Java classes generated before `classLoader` was added. @JvmStatic fun , B : Message.Builder> newMessageAdapter( type: Class, typeUrl: String, syntax: Syntax, - ): ProtoAdapter { - return createRuntimeMessageAdapter(type, typeUrl, syntax) - } + ): ProtoAdapter = createRuntimeMessageAdapter(type, typeUrl, syntax) /** Creates a new proto adapter for `type`. */ @JvmStatic fun , B : Message.Builder> newMessageAdapter( @@ -247,19 +215,13 @@ actual abstract class ProtoAdapter actual constructor( typeUrl: String, syntax: Syntax, classLoader: ClassLoader?, - ): ProtoAdapter { - return createRuntimeMessageAdapter(type, typeUrl, syntax, classLoader) - } + ): ProtoAdapter = createRuntimeMessageAdapter(type, typeUrl, syntax, classLoader) /** Creates a new proto adapter for `type`. */ - @JvmStatic fun newEnumAdapter(type: Class): EnumAdapter { - return RuntimeEnumAdapter(type) - } + @JvmStatic fun newEnumAdapter(type: Class): EnumAdapter = RuntimeEnumAdapter(type) /** Returns the adapter for the type of `Message`. */ - @JvmStatic fun > get(message: M): ProtoAdapter { - return get(message.javaClass) - } + @JvmStatic fun > get(message: M): ProtoAdapter = get(message.javaClass) /** Returns the adapter for `type`. */ @JvmStatic fun get(type: Class): ProtoAdapter { @@ -278,9 +240,7 @@ actual abstract class ProtoAdapter actual constructor( * message field's [WireField] annotation in the form * `com.squareup.wire.protos.person.Person#ADAPTER`. */ - @JvmStatic fun get(adapterString: String): ProtoAdapter<*> { - return get(adapterString, ProtoAdapter::class.java.classLoader) - } + @JvmStatic fun get(adapterString: String): ProtoAdapter<*> = get(adapterString, ProtoAdapter::class.java.classLoader) /** * Returns the adapter for a given `adapterString`, using [classLoader]. `adapterString` is specified on a @@ -403,22 +363,17 @@ actual abstract class ProtoAdapter actual constructor( * such as [Duration] and [Instant]. This proto adapter is used when the corresponding * `java.time` type is missing from the JVM classpath. */ - class UnsupportedTypeProtoAdapter : ProtoAdapter( - FieldEncoding.LENGTH_DELIMITED, - Nothing::class, - ) { - override fun redact(value: Nothing) = - throw IllegalStateException("Operation not supported.") - override fun encodedSize(value: Nothing) = - throw IllegalStateException("Operation not supported.") - override fun encode(writer: ProtoWriter, value: Nothing) = - throw IllegalStateException("Operation not supported.") - override fun encode(writer: ReverseProtoWriter, value: Nothing) = - throw IllegalStateException("Operation not supported.") - override fun decode(reader: ProtoReader): Nothing = - throw IllegalStateException("Operation not supported.") - override fun decode(reader: ProtoReader32): Nothing = - throw IllegalStateException("Operation not supported.") + class UnsupportedTypeProtoAdapter : + ProtoAdapter( + FieldEncoding.LENGTH_DELIMITED, + Nothing::class, + ) { + override fun redact(value: Nothing) = throw IllegalStateException("Operation not supported.") + override fun encodedSize(value: Nothing) = throw IllegalStateException("Operation not supported.") + override fun encode(writer: ProtoWriter, value: Nothing) = throw IllegalStateException("Operation not supported.") + override fun encode(writer: ReverseProtoWriter, value: Nothing) = throw IllegalStateException("Operation not supported.") + override fun decode(reader: ProtoReader): Nothing = throw IllegalStateException("Operation not supported.") + override fun decode(reader: ProtoReader32): Nothing = throw IllegalStateException("Operation not supported.") } } } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/RuntimeEnumAdapter.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/RuntimeEnumAdapter.kt index f3d99dcf5b..61c8b61d05 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/RuntimeEnumAdapter.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/RuntimeEnumAdapter.kt @@ -30,10 +30,8 @@ class RuntimeEnumAdapter internal constructor( private var fromValueMethod: Method? = null // Lazy to avoid reflection during class loading. - private fun getFromValueMethod(): Method { - return fromValueMethod ?: javaType.getMethod("fromValue", Int::class.javaPrimitiveType).also { - fromValueMethod = it - } + private fun getFromValueMethod(): Method = fromValueMethod ?: javaType.getMethod("fromValue", Int::class.javaPrimitiveType).also { + fromValueMethod = it } @Suppress("UNCHECKED_CAST") diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/-Platform.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/-Platform.kt index fbd38593dc..7ef7c8afd7 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/-Platform.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/-Platform.kt @@ -39,24 +39,22 @@ actual inline fun MutableList.toUnmodifiableList(): List = actual inline fun MutableMap.toUnmodifiableMap(): Map = Collections.unmodifiableMap(this) -actual fun camelCase(string: String, upperCamel: Boolean): String { - return buildString(string.length) { - var index = 0 - var uppercase = upperCamel - while (index < string.length) { - var codePoint = string.codePointAt(index) - - index += Character.charCount(codePoint) - - if (codePoint == '_'.code) { - uppercase = true - continue - } - if (uppercase) { - if (codePoint in 'a'.code..'z'.code) codePoint += 'A' - 'a' - } - appendCodePoint(codePoint) - uppercase = false +actual fun camelCase(string: String, upperCamel: Boolean): String = buildString(string.length) { + var index = 0 + var uppercase = upperCamel + while (index < string.length) { + var codePoint = string.codePointAt(index) + + index += Character.charCount(codePoint) + + if (codePoint == '_'.code) { + uppercase = true + continue + } + if (uppercase) { + if (codePoint in 'a'.code..'z'.code) codePoint += 'A' - 'a' } + appendCodePoint(codePoint) + uppercase = false } } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/EnumJsonFormatter.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/EnumJsonFormatter.kt index fc90795aaa..1aaa241eba 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/EnumJsonFormatter.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/EnumJsonFormatter.kt @@ -92,14 +92,10 @@ class EnumJsonFormatter( valueToString = mutableValueToString } - override fun fromString(value: String): E? { - return stringToValue[value] - // In case the `Unrecognized` instance is generated, we store the value assuming it represents - // a constant value (integer), and ignore it otherwise (name as string). - ?: value.toIntOrNull()?.let { value -> unrecognizedClassConstructor?.newInstance(value) } - } + override fun fromString(value: String): E? = stringToValue[value] + // In case the `Unrecognized` instance is generated, we store the value assuming it represents + // a constant value (integer), and ignore it otherwise (name as string). + ?: value.toIntOrNull()?.let { value -> unrecognizedClassConstructor?.newInstance(value) } - override fun toStringOrNumber(value: E): Any { - return valueToString[value] ?: value.value - } + override fun toStringOrNumber(value: E): Any = valueToString[value] ?: value.value } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt index 163e1bc0e2..d886f8edfb 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt @@ -58,52 +58,48 @@ class FieldBinding, B : Message.Builder> internal constr override val isMessage: Boolean get() = Message::class.java.isAssignableFrom(singleAdapter.type?.javaObjectType!!) - private fun getBuilderSetter(builderType: Class<*>, wireField: WireField): (B, Any?) -> Unit { - return when { - builderType.isAssignableFrom(KotlinConstructorBuilder::class.java) -> { builder, value -> - (builder as KotlinConstructorBuilder<*, *>).set(wireField, value) - } - wireField.label.isOneOf -> { - val type = messageField.type - val method = try { - builderType.getMethod(name, type) - } catch (_: NoSuchMethodException) { - throw AssertionError("No builder method ${builderType.name}.$name(${type.name})") - } - { builder, value -> - method.invoke(builder, value) - } + private fun getBuilderSetter(builderType: Class<*>, wireField: WireField): (B, Any?) -> Unit = when { + builderType.isAssignableFrom(KotlinConstructorBuilder::class.java) -> { builder, value -> + (builder as KotlinConstructorBuilder<*, *>).set(wireField, value) + } + wireField.label.isOneOf -> { + val type = messageField.type + val method = try { + builderType.getMethod(name, type) + } catch (_: NoSuchMethodException) { + throw AssertionError("No builder method ${builderType.name}.$name(${type.name})") } - else -> { - val field = try { - builderType.getField(name) - } catch (_: NoSuchFieldException) { - throw AssertionError("No builder field ${builderType.name}.$name") - } - { builder, value -> - field.set(builder, value) - } + { builder, value -> + method.invoke(builder, value) } } - } - - private fun getBuilderGetter(builderType: Class<*>, wireField: WireField): (B) -> Any? { - return if (builderType.isAssignableFrom(KotlinConstructorBuilder::class.java)) { - { builder -> - (builder as KotlinConstructorBuilder<*, *>).get(wireField) - } - } else { + else -> { val field = try { builderType.getField(name) } catch (_: NoSuchFieldException) { throw AssertionError("No builder field ${builderType.name}.$name") } - { builder -> - field.get(builder) + { builder, value -> + field.set(builder, value) } } } + private fun getBuilderGetter(builderType: Class<*>, wireField: WireField): (B) -> Any? = if (builderType.isAssignableFrom(KotlinConstructorBuilder::class.java)) { + { builder -> + (builder as KotlinConstructorBuilder<*, *>).get(wireField) + } + } else { + val field = try { + builderType.getField(name) + } catch (_: NoSuchFieldException) { + throw AssertionError("No builder field ${builderType.name}.$name") + } + { builder -> + field.get(builder) + } + } + private fun getInstanceGetter(messageType: Class): (M) -> Any? { if (Modifier.isPrivate(messageField.modifiers)) { val fieldName = messageField.name diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/InstantJsonFormatter.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/InstantJsonFormatter.kt index bb16bb8cf4..c2bcf7c1f5 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/InstantJsonFormatter.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/InstantJsonFormatter.kt @@ -26,9 +26,7 @@ import java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME * > fractional digits. Offsets other than "Z" are also accepted. */ object InstantJsonFormatter : JsonFormatter { - override fun toStringOrNumber(value: Instant): Any { - return ISO_INSTANT.format(value) - } + override fun toStringOrNumber(value: Instant): Any = ISO_INSTANT.format(value) override fun fromString(value: String): Instant { val parsed = ISO_OFFSET_DATE_TIME.parse(value) diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/JsonIntegration.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/JsonIntegration.kt index b14b013115..83274a610a 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/JsonIntegration.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/JsonIntegration.kt @@ -132,25 +132,23 @@ abstract class JsonIntegration { } } - private fun mapKeyJsonFormatter(protoAdapter: ProtoAdapter<*>): JsonFormatter<*> { - return when (protoAdapter) { - ProtoAdapter.STRING -> StringJsonFormatter - ProtoAdapter.INT32, - ProtoAdapter.SINT32, - ProtoAdapter.SFIXED32, - -> IntAsStringJsonFormatter - ProtoAdapter.FIXED32, - ProtoAdapter.UINT32, - -> UnsignedIntAsStringJsonFormatter - ProtoAdapter.INT64, - ProtoAdapter.SFIXED64, - ProtoAdapter.SINT64, - -> LongAsStringJsonFormatter - ProtoAdapter.FIXED64, - ProtoAdapter.UINT64, - -> UnsignedLongAsStringJsonFormatter - else -> error("Unexpected map key type: ${protoAdapter.type}") - } + private fun mapKeyJsonFormatter(protoAdapter: ProtoAdapter<*>): JsonFormatter<*> = when (protoAdapter) { + ProtoAdapter.STRING -> StringJsonFormatter + ProtoAdapter.INT32, + ProtoAdapter.SINT32, + ProtoAdapter.SFIXED32, + -> IntAsStringJsonFormatter + ProtoAdapter.FIXED32, + ProtoAdapter.UINT32, + -> UnsignedIntAsStringJsonFormatter + ProtoAdapter.INT64, + ProtoAdapter.SFIXED64, + ProtoAdapter.SINT64, + -> LongAsStringJsonFormatter + ProtoAdapter.FIXED64, + ProtoAdapter.UINT64, + -> UnsignedLongAsStringJsonFormatter + else -> error("Unexpected map key type: ${protoAdapter.type}") } /** Encodes a unsigned value without quotes, like `123`. */ @@ -171,39 +169,36 @@ abstract class JsonIntegration { } } - override fun toStringOrNumber(value: Long): Any { - return when { - value < 0L -> power64.add(BigInteger.valueOf(value)) - else -> value - } + override fun toStringOrNumber(value: Long): Any = when { + value < 0L -> power64.add(BigInteger.valueOf(value)) + else -> value } } /** Encodes an unsigned value with quotes, like `"123"`. */ private object UnsignedLongAsStringJsonFormatter : JsonFormatter { - override fun toStringOrNumber(value: Long) = - UnsignedLongAsNumberJsonFormatter.toStringOrNumber(value).toString() + override fun toStringOrNumber(value: Long) = UnsignedLongAsNumberJsonFormatter.toStringOrNumber(value).toString() - override fun fromString(value: String) = - UnsignedLongAsNumberJsonFormatter.fromString(value) + override fun fromString(value: String) = UnsignedLongAsNumberJsonFormatter.fromString(value) } /** Encodes an signed value with quotes, like `"-123"`. */ private object LongAsStringJsonFormatter : JsonFormatter { override fun toStringOrNumber(value: Long) = value.toString() - override fun fromString(value: String): Long { - return try { - value.toLong() - } catch (e: Exception) { - BigDecimal(value).longValueExact() // Handle extra trailing values like 5.0. - } + override fun fromString(value: String): Long = try { + value.toLong() + } catch (e: Exception) { + BigDecimal(value).longValueExact() // Handle extra trailing values like 5.0. } } /** Encodes a unsigned value without quotes, like `123`. */ private object UnsignedIntAsNumberJsonFormatter : JsonFormatter { // 2^32, used to convert sint32 values >= 2^31 to unsigned decimal form + @Suppress("ktlint:standard:property-naming") private const val power32 = 1L shl 32 + + @Suppress("ktlint:standard:property-naming") private const val maxInt = Int.MAX_VALUE.toLong() override fun fromString(value: String): Int { @@ -214,26 +209,23 @@ abstract class JsonIntegration { } } - override fun toStringOrNumber(value: Int): Any { - return when { - value < 0 -> value + power32 - else -> value - } + override fun toStringOrNumber(value: Int): Any = when { + value < 0 -> value + power32 + else -> value } } /** Encodes an unsigned value with quotes, like `"123"`. */ private object UnsignedIntAsStringJsonFormatter : JsonFormatter { // 2^32, used to convert sint32 values >= 2^31 to unsigned decimal form + @Suppress("ktlint:standard:property-naming") private const val power32 = 1L shl 32 override fun fromString(value: String) = value.toLong().toInt() - override fun toStringOrNumber(value: Int): Any { - return when { - value < 0 -> (value + power32).toString() - else -> value.toString() - } + override fun toStringOrNumber(value: Int): Any = when { + value < 0 -> (value + power32).toString() + else -> value.toString() } } diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/reflection.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/reflection.kt index 0bec418f65..442dbd91b3 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/reflection.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/reflection.kt @@ -109,12 +109,10 @@ fun , B : Message.Builder> createRuntimeMessageAdapter( @Suppress("UNCHECKED_CAST") private fun , B : Message.Builder> getBuilderType( messageType: Class, -): Class { - return runCatching { - Class.forName("${messageType.name}\$Builder", false, messageType.classLoader) as Class - } - .getOrNull() ?: KotlinConstructorBuilder::class.java as Class +): Class = runCatching { + Class.forName("${messageType.name}\$Builder", false, messageType.classLoader) as Class } + .getOrNull() ?: KotlinConstructorBuilder::class.java as Class private class RuntimeMessageBinding, B : Message.Builder>( override val messageType: KClass, @@ -135,9 +133,7 @@ private class RuntimeMessageBinding, B : Message.Builder override fun newBuilder(): B = createBuilder() - override fun build(builder: B): M { - return builder.build() - } + override fun build(builder: B): M = builder.build() override fun addUnknownField(builder: B, tag: Int, fieldEncoding: FieldEncoding, value: Any?) { builder.addUnknownField(tag, fieldEncoding, value) diff --git a/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt b/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt index 61cf08291a..404d6f9ab3 100644 --- a/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt +++ b/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/ProtoAdapter.kt @@ -52,9 +52,7 @@ actual abstract class ProtoAdapter actual constructor( * length-delimited prefix (should the type require one), and value. Returns 0 if `value` is * null. */ - actual open fun encodedSizeWithTag(tag: Int, value: E?): Int { - return commonEncodedSizeWithTag(tag, value) - } + actual open fun encodedSizeWithTag(tag: Int, value: E?): Int = commonEncodedSizeWithTag(tag, value) /** Write non-null `value` to `writer`. */ actual abstract fun encode(writer: ProtoWriter, value: E) @@ -80,54 +78,34 @@ actual abstract class ProtoAdapter actual constructor( } /** Encode `value` as a `byte[]`. */ - actual fun encode(value: E): ByteArray { - return commonEncode(value) - } + actual fun encode(value: E): ByteArray = commonEncode(value) /** Encode `value` as a [ByteString]. */ - actual fun encodeByteString(value: E): ByteString { - return commonEncodeByteString(value) - } + actual fun encodeByteString(value: E): ByteString = commonEncodeByteString(value) /** Read a non-null value from `reader`. */ actual abstract fun decode(reader: ProtoReader): E /** Read a non-null value from `reader`. */ - actual open fun decode(reader: ProtoReader32): E { - return decode(reader.asProtoReader()) - } + actual open fun decode(reader: ProtoReader32): E = decode(reader.asProtoReader()) /** Read an encoded message from `bytes`. */ - actual fun decode(bytes: ByteArray): E { - return commonDecode(bytes) - } + actual fun decode(bytes: ByteArray): E = commonDecode(bytes) /** Read an encoded message from `bytes`. */ - actual fun decode(bytes: ByteString): E { - return commonDecode(bytes) - } + actual fun decode(bytes: ByteString): E = commonDecode(bytes) /** Read an encoded message from `source`. */ - actual fun decode(source: BufferedSource): E { - return commonDecode(source) - } + actual fun decode(source: BufferedSource): E = commonDecode(source) - actual fun tryDecode(reader: ProtoReader, destination: MutableList) { - return commonTryDecode(reader, destination) - } + actual fun tryDecode(reader: ProtoReader, destination: MutableList) = commonTryDecode(reader, destination) - actual fun tryDecode(reader: ProtoReader32, destination: MutableList) { - return commonTryDecode(reader, destination) - } + actual fun tryDecode(reader: ProtoReader32, destination: MutableList) = commonTryDecode(reader, destination) /** Returns a human-readable version of the given `value`. */ - actual open fun toString(value: E): String { - return commonToString(value) - } + actual open fun toString(value: E): String = commonToString(value) - internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> { - return commonWithLabel(label) - } + internal actual fun withLabel(label: WireField.Label): ProtoAdapter<*> = commonWithLabel(label) /** Returns an adapter for `E` but as a packed, repeated value. */ actual fun asPacked(): ProtoAdapter> { @@ -146,11 +124,9 @@ actual abstract class ProtoAdapter actual constructor( * the returned adapter, only single-element lists will be returned and it is the caller's * responsibility to merge them into the final list. */ - actual fun asRepeated(): ProtoAdapter> { - return repeatedAdapter ?: throw UnsupportedOperationException( - "Can't create a repeated adapter from a repeated or packed adapter.", - ) - } + actual fun asRepeated(): ProtoAdapter> = repeatedAdapter ?: throw UnsupportedOperationException( + "Can't create a repeated adapter from a repeated or packed adapter.", + ) actual class EnumConstantNotFoundException actual constructor( actual val value: Int, @@ -168,9 +144,7 @@ actual abstract class ProtoAdapter actual constructor( actual fun newMapAdapter( keyAdapter: ProtoAdapter, valueAdapter: ProtoAdapter, - ): ProtoAdapter> { - return commonNewMapAdapter(keyAdapter, valueAdapter) - } + ): ProtoAdapter> = commonNewMapAdapter(keyAdapter, valueAdapter) actual val BOOL: ProtoAdapter = commonBool() diff --git a/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/internal/-Platform.kt b/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/internal/-Platform.kt index ef30a205d5..28ba62cc3e 100644 --- a/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/internal/-Platform.kt +++ b/wire-runtime/src/nonJvmMain/kotlin/com/squareup/wire/internal/-Platform.kt @@ -41,24 +41,22 @@ actual inline fun MutableList.toUnmodifiableList(): List = this actual inline fun MutableMap.toUnmodifiableMap(): Map = this // TODO: Use code points to process each char. -actual fun camelCase(string: String, upperCamel: Boolean): String { - return buildString(string.length) { - var index = 0 - var uppercase = upperCamel - while (index < string.length) { - var char = string[index] +actual fun camelCase(string: String, upperCamel: Boolean): String = buildString(string.length) { + var index = 0 + var uppercase = upperCamel + while (index < string.length) { + var char = string[index] - index++ + index++ - if (char == '_') { - uppercase = true - continue - } - if (uppercase) { - if (char in 'a'..'z') char += 'A' - 'a' - } - append(char) - uppercase = false + if (char == '_') { + uppercase = true + continue } + if (uppercase) { + if (char in 'a'..'z') char += 'A' - 'a' + } + append(char) + uppercase = false } } diff --git a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt index 7e194ba482..4b2d5a5e6d 100644 --- a/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt +++ b/wire-schema-tests/src/commonMain/kotlin/com/squareup/wire/SchemaBuilder.kt @@ -43,9 +43,7 @@ class SchemaBuilder { * @param name The qualified name of the file. * @param protoFile The content of the file. */ - fun add(name: Path, protoFile: String): SchemaBuilder { - return add(name, protoFile, sourcePath) - } + fun add(name: Path, protoFile: String): SchemaBuilder = add(name, protoFile, sourcePath) /** * Add a file to be loaded into the schema. @@ -75,9 +73,7 @@ class SchemaBuilder { } /** Add a file to be linked against, but not used to generate artifacts. */ - fun addProtoPath(name: Path, protoFile: String): SchemaBuilder { - return add(name, protoFile, protoPath) - } + fun addProtoPath(name: Path, protoFile: String): SchemaBuilder = add(name, protoFile, protoPath) /** See [SchemaLoader.opaqueTypes]. */ fun addOpaqueTypes(vararg opaqueTypes: ProtoType): SchemaBuilder { @@ -97,9 +93,7 @@ class SchemaBuilder { } /** Builds a schema out of written `.proto` files. */ -inline fun buildSchema(builderAction: SchemaBuilder.() -> Unit): Schema { - return SchemaBuilder().apply(builderAction).build() -} +inline fun buildSchema(builderAction: SchemaBuilder.() -> Unit): Schema = SchemaBuilder().apply(builderAction).build() /** * Wire loads runtime protos such as `google/protobuf/descriptor.proto` when it needs to load a diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt index 6eb424bd0a..26ee783082 100644 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt +++ b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/LogToWireLoggerHandler.kt @@ -44,7 +44,5 @@ class LogToWireLoggerHandler : SchemaHandler() { return listOf() } - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? { - return null - } + override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = null } diff --git a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt index 09656227e1..3d259b8dc7 100644 --- a/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt +++ b/wire-schema-tests/src/commonTest/kotlin/com/squareup/wire/recipes/MarkdownHandler.kt @@ -25,17 +25,11 @@ import okio.Path /** Sample schema handler which generate Markdown files for types and services. */ class MarkdownHandler : SchemaHandler() { - override fun handle(type: Type, context: SchemaHandler.Context): Path { - return writeMarkdownFile(type.type, toMarkdown(type), context) - } + override fun handle(type: Type, context: SchemaHandler.Context): Path = writeMarkdownFile(type.type, toMarkdown(type), context) - override fun handle(service: Service, context: SchemaHandler.Context): List { - return listOf(writeMarkdownFile(service.type, toMarkdown(service), context)) - } + override fun handle(service: Service, context: SchemaHandler.Context): List = listOf(writeMarkdownFile(service.type, toMarkdown(service), context)) - override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? { - return null - } + override fun handle(extend: Extend, field: Field, context: SchemaHandler.Context): Path? = null private fun writeMarkdownFile( protoType: ProtoType, @@ -60,21 +54,17 @@ class MarkdownHandler : SchemaHandler() { return result } - private fun toMarkdown(type: Type): String { - return """ + private fun toMarkdown(type: Type): String = """ |# ${type.type.simpleName} | |${type.documentation} | - """.trimMargin() - } + """.trimMargin() - private fun toMarkdown(service: Service): String { - return """ + private fun toMarkdown(service: Service): String = """ |# ${service.type.simpleName} | |${service.documentation} | - """.trimMargin() - } + """.trimMargin() } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CoreLoader.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CoreLoader.kt index d251d75503..cb17ec7a58 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CoreLoader.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CoreLoader.kt @@ -26,21 +26,17 @@ expect object CoreLoader : Loader { override fun withErrors(errors: ErrorCollector): Loader } -fun isWireRuntimeProto(location: Location): Boolean { - return location.base == WIRE_RUNTIME_JAR && isWireRuntimeProto(location.path) -} +fun isWireRuntimeProto(location: Location): Boolean = location.base == WIRE_RUNTIME_JAR && isWireRuntimeProto(location.path) /** Returns true if [path] is bundled in the wire runtime. */ -fun isWireRuntimeProto(path: String): Boolean { - return path == ANY_PROTO || - path == DESCRIPTOR_PROTO || - path == DURATION_PROTO || - path == EMPTY_PROTO || - path == STRUCT_PROTO || - path == TIMESTAMP_PROTO || - path == WRAPPERS_PROTO || - path == WIRE_EXTENSIONS_PROTO -} +fun isWireRuntimeProto(path: String): Boolean = path == ANY_PROTO || + path == DESCRIPTOR_PROTO || + path == DURATION_PROTO || + path == EMPTY_PROTO || + path == STRUCT_PROTO || + path == TIMESTAMP_PROTO || + path == WRAPPERS_PROTO || + path == WIRE_EXTENSIONS_PROTO internal const val DESCRIPTOR_PROTO = "google/protobuf/descriptor.proto" internal const val WIRE_EXTENSIONS_PROTO = "wire/extensions.proto" diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CycleChecker.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CycleChecker.kt index e224503d87..979237bde6 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CycleChecker.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/CycleChecker.kt @@ -57,23 +57,21 @@ internal class CycleChecker( } /** Returns an error message that describes cyclic imports in [files]. */ - private fun importCycleMessageError(files: List): String { - return buildString { - append("imports form a cycle:") - - for (file in files) { - val fileLinker = fileLinkers[file] ?: continue - - append("\n $file:") - for (import in fileLinker.protoFile.imports) { - if (import in files) { - append("\n import \"$import\";") - } + private fun importCycleMessageError(files: List): String = buildString { + append("imports form a cycle:") + + for (file in files) { + val fileLinker = fileLinkers[file] ?: continue + + append("\n $file:") + for (import in fileLinker.protoFile.imports) { + if (import in files) { + append("\n import \"$import\";") } - for (import in fileLinker.protoFile.publicImports) { - if (import in files) { - append("\n import public \"$import\";") - } + } + for (import in fileLinker.protoFile.publicImports) { + if (import in files) { + append("\n import public \"$import\";") } } } @@ -124,39 +122,37 @@ internal class CycleChecker( * import "locations/residence.proto"; * ``` */ - private fun packagesCycleMessageError(packages: List): String { - return buildString { - append("packages form a cycle:") - - val sortedFileLinkers = fileLinkers.entries.sortedBy { it.value.cycleCheckPackageName } - - var lastSourcePackage: String? = null - var lastTargetPackage: String? = null - var lastSourcePath: String? = null - - for ((sourcePath, sourceFileLinker) in sortedFileLinkers) { - val sourcePackage = sourceFileLinker.cycleCheckPackageName - if (sourcePackage !in packages) continue - - for (targetPath in sourceFileLinker.importsAndPublicImports) { - val targetFileLinker = fileLinkers[targetPath] ?: continue - val targetPackage = targetFileLinker.cycleCheckPackageName - if (targetPackage == sourcePackage || targetPackage !in packages) continue - - if (lastSourcePackage != sourcePackage || lastTargetPackage != targetPackage) { - append("\n $sourcePackage imports $targetPackage") - lastSourcePackage = sourcePackage - lastTargetPackage = targetPackage - lastSourcePath = null - } - - if (lastSourcePath != sourcePath) { - append("\n $sourcePath:") - lastSourcePath = sourcePath - } - - append("\n import \"$targetPath\";") + private fun packagesCycleMessageError(packages: List): String = buildString { + append("packages form a cycle:") + + val sortedFileLinkers = fileLinkers.entries.sortedBy { it.value.cycleCheckPackageName } + + var lastSourcePackage: String? = null + var lastTargetPackage: String? = null + var lastSourcePath: String? = null + + for ((sourcePath, sourceFileLinker) in sortedFileLinkers) { + val sourcePackage = sourceFileLinker.cycleCheckPackageName + if (sourcePackage !in packages) continue + + for (targetPath in sourceFileLinker.importsAndPublicImports) { + val targetFileLinker = fileLinkers[targetPath] ?: continue + val targetPackage = targetFileLinker.cycleCheckPackageName + if (targetPackage == sourcePackage || targetPackage !in packages) continue + + if (lastSourcePackage != sourcePackage || lastTargetPackage != targetPackage) { + append("\n $sourcePackage imports $targetPackage") + lastSourcePackage = sourcePackage + lastTargetPackage = targetPackage + lastSourcePath = null } + + if (lastSourcePath != sourcePath) { + append("\n $sourcePath:") + lastSourcePath = sourcePath + } + + append("\n import \"$targetPath\";") } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumConstant.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumConstant.kt index bfbeffcd3b..31e5d8bc6e 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumConstant.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumConstant.kt @@ -28,8 +28,7 @@ data class EnumConstant( val isDeprecated: Boolean get() = "true" == options.get(DEPRECATED) - internal fun toElement() = - EnumConstantElement(location, name, tag, documentation, options.elements) + internal fun toElement() = EnumConstantElement(location, name, tag, documentation, options.elements) internal fun linkOptions(linker: Linker, validate: Boolean) { @Suppress("NAME_SHADOWING") @@ -42,22 +41,20 @@ data class EnumConstant( markSet: MarkSet, ) = EnumConstant(location, name, tag, documentation, options.retainAll(schema, markSet)) - internal fun retainLinked() = - EnumConstant(location, name, tag, documentation, options.retainLinked()) + internal fun retainLinked() = EnumConstant(location, name, tag, documentation, options.retainLinked()) companion object { private val DEPRECATED = ProtoMember.get(ENUM_VALUE_OPTIONS, "deprecated") - internal fun fromElements(elements: List) = - elements.map { - EnumConstant( - it.location, - it.name, - it.tag, - it.documentation, - Options(ENUM_VALUE_OPTIONS, it.options), - ) - } + internal fun fromElements(elements: List) = elements.map { + EnumConstant( + it.location, + it.name, + it.tag, + it.documentation, + Options(ENUM_VALUE_OPTIONS, it.options), + ) + } internal fun toElements(constants: List) = constants.map { it.toElement() } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumType.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumType.kt index ba22e00a91..540b17138e 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumType.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/EnumType.kt @@ -187,16 +187,14 @@ data class EnumType( ) } - fun toElement(): EnumElement { - return EnumElement( - location = location, - name = name, - documentation = documentation, - options = options.elements, - constants = toElements(constants), - reserveds = toElements(reserveds), - ) - } + fun toElement(): EnumElement = EnumElement( + location = location, + name = name, + documentation = documentation, + options = options.elements, + constants = toElements(constants), + reserveds = toElements(reserveds), + ) companion object { internal val ALLOW_ALIAS = ProtoMember.get(ENUM_OPTIONS, "allow_alias") @@ -208,17 +206,15 @@ data class EnumType( protoType: ProtoType, enumElement: EnumElement, syntax: Syntax, - ): EnumType { - return EnumType( - type = protoType, - location = enumElement.location, - documentation = enumElement.documentation, - name = enumElement.name, - constants = EnumConstant.fromElements(enumElement.constants), - options = Options(ENUM_OPTIONS, enumElement.options), - syntax = syntax, - reserveds = fromElements(enumElement.reserveds), - ) - } + ): EnumType = EnumType( + type = protoType, + location = enumElement.location, + documentation = enumElement.documentation, + name = enumElement.name, + constants = EnumConstant.fromElements(enumElement.constants), + options = Options(ENUM_OPTIONS, enumElement.options), + syntax = syntax, + reserveds = fromElements(enumElement.reserveds), + ) } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Extensions.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Extensions.kt index c52ae93242..73bd6a8674 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Extensions.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Extensions.kt @@ -50,11 +50,9 @@ data class Extensions( companion object { @JvmStatic - fun fromElements(elements: List) = - elements.map { Extensions(it.location, it.documentation, it.values) } + fun fromElements(elements: List) = elements.map { Extensions(it.location, it.documentation, it.values) } @JvmStatic - fun toElements(extensions: List) = - extensions.map { ExtensionsElement(it.location, it.documentation, it.values) } + fun toElements(extensions: List) = extensions.map { ExtensionsElement(it.location, it.documentation, it.values) } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Field.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Field.kt index 75b36370ff..c353a904a2 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Field.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Field.kt @@ -114,11 +114,9 @@ data class Field( var jsonName: String? = null private set - private fun isPackable(linker: Linker, type: ProtoType): Boolean { - return type != ProtoType.STRING && - type != ProtoType.BYTES && - linker.get(type) !is MessageType - } + private fun isPackable(linker: Linker, type: ProtoType): Boolean = type != ProtoType.STRING && + type != ProtoType.BYTES && + linker.get(type) !is MessageType fun link(linker: Linker) { type = linker.withContext(this).resolveType(elementType) diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Linker.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Linker.kt index 56aad8c881..0bc87016fa 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Linker.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Linker.kt @@ -212,14 +212,10 @@ class Linker { } /** Returns the type name for the scalar, relative or fully-qualified name [name]. */ - fun resolveType(name: String): ProtoType { - return resolveType(name, false) - } + fun resolveType(name: String): ProtoType = resolveType(name, false) /** Returns the type name for the relative or fully-qualified name [name]. */ - fun resolveMessageType(name: String): ProtoType { - return resolveType(name, true) - } + fun resolveMessageType(name: String): ProtoType = resolveType(name, true) private fun resolveType( name: String, diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Location.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Location.kt index ab04e34e71..370b3ecbf4 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Location.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Location.kt @@ -61,16 +61,12 @@ data class Location( companion object { @JvmStatic - fun get(path: String): Location { - return get("", path) - } + fun get(path: String): Location = get("", path) @JvmStatic fun get( base: String, path: String, - ): Location { - return Location(base.trimEnd('/'), path, -1, -1) - } + ): Location = Location(base.trimEnd('/'), path, -1, -1) } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MarkSet.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MarkSet.kt index a5ec887575..ec350217f4 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MarkSet.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MarkSet.kt @@ -99,9 +99,7 @@ class MarkSet( } /** Returns true if `type` is marked and should be retained. */ - operator fun contains(type: ProtoType): Boolean { - return types.contains(type) - } + operator fun contains(type: ProtoType): Boolean = types.contains(type) /** Returns true if `member` is marked and should be retained. */ operator fun contains(protoMember: ProtoMember): Boolean { @@ -109,7 +107,8 @@ class MarkSet( // We do not contain non-root members whose referenced type is excluded. if (!rootMemberTypes.containsKey(protoMember) && - memberType != null && pruningRules.prunes(memberType) + memberType != null && + pruningRules.prunes(memberType) ) { return false } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MessageType.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MessageType.kt index cd7508da7b..f4ac65a1d3 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MessageType.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/MessageType.kt @@ -83,12 +83,10 @@ data class MessageType( * Returns the field with the qualified name [qualifiedName], or null if this type has no * such field. */ - fun extensionField(qualifiedName: String): Field? = - extensionFields.firstOrNull { it.qualifiedName == qualifiedName } + fun extensionField(qualifiedName: String): Field? = extensionFields.firstOrNull { it.qualifiedName == qualifiedName } /** Returns the oneOf named [name], or null if this type has no such oneOf. */ - fun oneOf(name: String): OneOf? = - oneOfs.firstOrNull { it.name == name } + fun oneOf(name: String): OneOf? = oneOfs.firstOrNull { it.name == name } /** Returns the field tagged [tag], or null if this type has no such field. */ fun field(tag: Int): Field? { @@ -231,21 +229,19 @@ data class MessageType( ) } - fun toElement(): MessageElement { - return MessageElement( - location = location, - name = name, - documentation = documentation, - nestedTypes = toElements(nestedTypes), - extendDeclarations = toElements(nestedExtendList), - options = options.elements, - reserveds = toElements(reserveds), - fields = toElements(declaredFields), - oneOfs = toElements(oneOfs), - extensions = toElements(extensionsList), - groups = emptyList(), - ) - } + fun toElement(): MessageElement = MessageElement( + location = location, + name = name, + documentation = documentation, + nestedTypes = toElements(nestedTypes), + extendDeclarations = toElements(nestedExtendList), + options = options.elements, + reserveds = toElements(reserveds), + fields = toElements(declaredFields), + oneOfs = toElements(oneOfs), + extensions = toElements(extensionsList), + groups = emptyList(), + ) companion object { internal val DEPRECATED = ProtoMember.get(MESSAGE_OPTIONS, "deprecated") diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/OneOf.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/OneOf.kt index 7f7b1cb6e3..69b0f9fbcc 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/OneOf.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/OneOf.kt @@ -77,16 +77,15 @@ data class OneOf( } @JvmStatic - fun toElements(oneOfs: List) = - oneOfs.map { - OneOfElement( - name = it.name, - documentation = it.documentation, - fields = Field.toElements(it.fields), - groups = emptyList(), - location = it.location, - options = it.options.elements, - ) - } + fun toElements(oneOfs: List) = oneOfs.map { + OneOfElement( + name = it.name, + documentation = it.documentation, + fields = Field.toElements(it.fields), + groups = emptyList(), + location = it.location, + options = it.options.elements, + ) + } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Options.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Options.kt index a6bcbc232a..1d66fb3115 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Options.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Options.kt @@ -47,9 +47,7 @@ class Options( fun retainLinked() = Options(optionType, emptyList()) - fun get(protoMember: ProtoMember): Any? { - return entries?.find { it.protoMember == protoMember }?.value - } + fun get(protoMember: ProtoMember): Any? = entries?.find { it.protoMember == protoMember }?.value /** * Returns true if any of the options in [entries] matches both of the regular expressions @@ -235,28 +233,24 @@ class Options( } } - private fun coerceValueForField(context: ProtoType, value: Any, isRepeated: Boolean): Any { - return when { - isRepeated || context.isMap -> value as? List<*> ?: listOf(value) - value is List<*> -> value.single()!! - else -> value - } + private fun coerceValueForField(context: ProtoType, value: Any, isRepeated: Boolean): Any = when { + isRepeated || context.isMap -> value as? List<*> ?: listOf(value) + value is List<*> -> value.single()!! + else -> value } /** Combine values for the same key, resolving conflicts based on their type. */ - private fun union(linker: Linker, a: Any, b: Any): Any { - return when (a) { - is List<*> -> a + b as List<*> + private fun union(linker: Linker, a: Any, b: Any): Any = when (a) { + is List<*> -> a + b as List<*> - is Map<*, *> -> { - @Suppress("UNCHECKED_CAST") // All maps have this type. - union(linker, a as Map, b as Map) - } + is Map<*, *> -> { + @Suppress("UNCHECKED_CAST") // All maps have this type. + union(linker, a as Map, b as Map) + } - else -> { - linker.errors += "conflicting options: $a, $b" - a // Just return any placeholder. - } + else -> { + linker.errors += "conflicting options: $a, $b" + a // Just return any placeholder. } } @@ -308,15 +302,11 @@ class Options( return result } - fun fields(): Multimap { - return fields(PruningRules.Builder().build()) - } + fun fields(): Multimap = fields(PruningRules.Builder().build()) - fun fields(pruningRules: PruningRules): Multimap { - return mutableMapOf>().also { - gatherFields(it, optionType, entries?.toMap(), pruningRules) - }.toMultimap() - } + fun fields(pruningRules: PruningRules): Multimap = mutableMapOf>().also { + gatherFields(it, optionType, entries?.toMap(), pruningRules) + }.toMultimap() private fun gatherFields( sink: MutableMap>, @@ -374,62 +364,60 @@ class Options( markSet: MarkSet, type: ProtoType?, o: Any?, - ): Any? { - return when { - o == null -> null - - o is Map<*, *> -> { - val map = mutableMapOf() - for ((key, value) in o) { - val protoMember = when (key) { - is ProtoMember -> key - else -> { - // When the key isn't a `ProtoMember`, this key/value pair is a inlined value of a map - // field. - val retainedValue = retainAll(schema, markSet, type, value) - // if `retainedValue` is a map, its value represents an inline message, and we need to - // mark the proto member. - if (retainedValue is Map<*, *>) { - for ((k, v) in retainedValue) { - map[k as ProtoMember] = v!! - } + ): Any? = when { + o == null -> null + + o is Map<*, *> -> { + val map = mutableMapOf() + for ((key, value) in o) { + val protoMember = when (key) { + is ProtoMember -> key + else -> { + // When the key isn't a `ProtoMember`, this key/value pair is a inlined value of a map + // field. + val retainedValue = retainAll(schema, markSet, type, value) + // if `retainedValue` is a map, its value represents an inline message, and we need to + // mark the proto member. + if (retainedValue is Map<*, *>) { + for ((k, v) in retainedValue) { + map[k as ProtoMember] = v!! } - continue } + continue } - val isCoreMemberOfGoogleProtobuf = - protoMember.type in GOOGLE_PROTOBUF_OPTION_TYPES && - !schema.isExtensionField(protoMember) - if (!markSet.contains(protoMember) && !isCoreMemberOfGoogleProtobuf) { - continue // Prune this field. - } + } + val isCoreMemberOfGoogleProtobuf = + protoMember.type in GOOGLE_PROTOBUF_OPTION_TYPES && + !schema.isExtensionField(protoMember) + if (!markSet.contains(protoMember) && !isCoreMemberOfGoogleProtobuf) { + continue // Prune this field. + } - val field = schema.getField(protoMember)!! - val retainedValue = retainAll(schema, markSet, field.type, value) - if (retainedValue != null) { - map[protoMember] = retainedValue // This retained field is non-empty. - } else if (isCoreMemberOfGoogleProtobuf) { - map[protoMember] = value!! - } + val field = schema.getField(protoMember)!! + val retainedValue = retainAll(schema, markSet, field.type, value) + if (retainedValue != null) { + map[protoMember] = retainedValue // This retained field is non-empty. + } else if (isCoreMemberOfGoogleProtobuf) { + map[protoMember] = value!! } - map.ifEmpty { null } } + map.ifEmpty { null } + } - o is List<*> -> { - val list = mutableListOf() - for (value in o) { - val retainedValue = retainAll(schema, markSet, type, value) - if (retainedValue != null) { - list.add(retainedValue) // This retained value is non-empty. - } + o is List<*> -> { + val list = mutableListOf() + for (value in o) { + val retainedValue = retainAll(schema, markSet, type, value) + if (retainedValue != null) { + list.add(retainedValue) // This retained value is non-empty. } - list.ifEmpty { null } } + list.ifEmpty { null } + } - !markSet.contains(type!!) -> null // Prune this type. + !markSet.contains(type!!) -> null // Prune this type. - else -> o - } + else -> o } companion object { @@ -520,7 +508,5 @@ class Options( } } - private fun List.toMap(): Map { - return associate { it.protoMember to it.value } - } + private fun List.toMap(): Map = associate { it.protoMember to it.value } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoFile.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoFile.kt index bc3743e5c9..ab55a5d897 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoFile.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoFile.kt @@ -36,20 +36,18 @@ data class ProtoFile( private var javaPackage: Any? = null private var wirePackage: Any? = null - fun toElement(): ProtoFileElement { - return ProtoFileElement( - location, - packageName, - syntax, - imports, - publicImports, - weakImports, - Type.toElements(types), - Service.toElements(services), - Extend.toElements(extendList), - options.elements, - ) - } + fun toElement(): ProtoFileElement = ProtoFileElement( + location, + packageName, + syntax, + imports, + publicImports, + weakImports, + Type.toElements(types), + Service.toElements(services), + Extend.toElements(extendList), + options.elements, + ) /** * Returns the name of this proto file, like `simple_message` for @@ -82,13 +80,9 @@ data class ProtoFile( return typesAndNestedTypes } - fun javaPackage(): String? { - return javaPackage?.toString() - } + fun javaPackage(): String? = javaPackage?.toString() - fun wirePackage(): String? { - return wirePackage?.toString() - } + fun wirePackage(): String? = wirePackage?.toString() /** * Returns a new proto file that omits types, services, extensions, and options not in @@ -206,7 +200,8 @@ data class ProtoFile( val retainedWeakImports = weakImports.filter { referencedImports.contains(it) } - return if (imports.size != retainedImports.size || publicImports.size != retainedPublicImports.size || + return if (imports.size != retainedImports.size || + publicImports.size != retainedPublicImports.size || weakImports.size != retainedWeakImports.size ) { val result = ProtoFile( @@ -227,13 +222,9 @@ data class ProtoFile( wirePackage = options.get(WIRE_PACKAGE) } - override fun toString(): String { - return location.path - } + override fun toString(): String = location.path - fun toSchema(): String { - return toElement().toSchema() - } + fun toSchema(): String = toElement().toSchema() companion object { val JAVA_PACKAGE = ProtoMember.get(Options.FILE_OPTIONS, "java_package") diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoMember.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoMember.kt index febd959ab5..3967f2ce2d 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoMember.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoMember.kt @@ -36,8 +36,7 @@ class ProtoMember private constructor( require(!type.isScalar) { "scalars cannot have members" } } - override fun equals(other: Any?) = - other is ProtoMember && type == other.type && member == other.member + override fun equals(other: Any?) = other is ProtoMember && type == other.type && member == other.member override fun hashCode() = type.hashCode() * 37 + member.hashCode() diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoType.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoType.kt index 1fd0980cf2..11ea414095 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoType.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/ProtoType.kt @@ -211,11 +211,9 @@ class ProtoType { ) @JvmStatic - fun get(enclosingTypeOrPackage: String?, typeName: String): ProtoType { - return when { - enclosingTypeOrPackage != null -> get("$enclosingTypeOrPackage.$typeName") - else -> get(typeName) - } + fun get(enclosingTypeOrPackage: String?, typeName: String): ProtoType = when { + enclosingTypeOrPackage != null -> get("$enclosingTypeOrPackage.$typeName") + else -> get(typeName) } @JvmStatic @@ -236,7 +234,6 @@ class ProtoType { return ProtoType(false, name) } - @JvmStatic fun get(keyType: ProtoType, valueType: ProtoType, name: String) = - ProtoType(keyType, valueType, name) + @JvmStatic fun get(keyType: ProtoType, valueType: ProtoType, name: String) = ProtoType(keyType, valueType, name) } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Pruner.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Pruner.kt index 607d9d0091..c45ef626fe 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Pruner.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Pruner.kt @@ -46,10 +46,8 @@ class Pruner( private fun retainAll( schema: Schema, marks: MarkSet, - ): List { - return schema.protoFiles.map { protoFile -> - protoFile.retainAll(schema, marks) - } + ): List = schema.protoFiles.map { protoFile -> + protoFile.retainAll(schema, marks) } private fun retainImports(protoFiles: List): List { diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/PruningRules.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/PruningRules.kt index f1f04f23cc..4dbeb3cf44 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/PruningRules.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/PruningRules.kt @@ -90,12 +90,10 @@ class PruningRules private constructor(builder: Builder) { get() = roots.isEmpty() && prunes.isEmpty() && _since == null && _until == null && _only == null /** Returns true unless [options] specifies a version that is outside of the configured range. */ - fun isFieldRetainedVersion(options: Options) = - isRetainedVersion(options, FIELD_SINCE, FIELD_UNTIL) + fun isFieldRetainedVersion(options: Options) = isRetainedVersion(options, FIELD_SINCE, FIELD_UNTIL) /** Returns true unless [options] specifies a version that is outside of the configured range. */ - fun isEnumConstantRetainedVersion(options: Options) = - isRetainedVersion(options, ENUM_CONSTANT_SINCE, ENUM_CONSTANT_UNTIL) + fun isEnumConstantRetainedVersion(options: Options) = isRetainedVersion(options, ENUM_CONSTANT_SINCE, ENUM_CONSTANT_UNTIL) private fun isRetainedVersion( options: Options, @@ -105,8 +103,12 @@ class PruningRules private constructor(builder: Builder) { if (_until != null || _only != null) { val sinceOption = options.get(sinceMember) val since = (sinceOption as? String)?.toLowerCaseSemVer() - if (_until != null && since != null && since >= _until || - _only != null && since != null && since > _only + if (_until != null && + since != null && + since >= _until || + _only != null && + since != null && + since > _only ) { return false } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Reserved.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Reserved.kt index bb21708841..fbac2277e5 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Reserved.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Reserved.kt @@ -31,11 +31,9 @@ data class Reserved( companion object { @JvmStatic - fun fromElements(elements: List) = - elements.map { Reserved(it.location, it.documentation, it.values) } + fun fromElements(elements: List) = elements.map { Reserved(it.location, it.documentation, it.values) } @JvmStatic - fun toElements(reserveds: List) = - reserveds.map { ReservedElement(it.location, it.documentation, it.values) } + fun toElements(reserveds: List) = reserveds.map { ReservedElement(it.location, it.documentation, it.values) } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Root.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Root.kt index e2badb06b9..9180bd4888 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Root.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Root.kt @@ -115,18 +115,16 @@ internal class DirectoryRoot( /** The root to search. If this is a .zip file this is within its internal file system. */ val rootDirectory: Path, ) : Root() { - override fun allProtoFiles(): Set { - return fileSystem.listRecursively(rootDirectory) - .filter { it.toString().endsWith(".proto") } - .map { descendant -> - val location = Location.get( - base = base, - path = descendant.relativeTo(rootDirectory).withUnixSlashes().toString(), - ) - ProtoFilePath(location, fileSystem, descendant) - } - .toSet() - } + override fun allProtoFiles(): Set = fileSystem.listRecursively(rootDirectory) + .filter { it.toString().endsWith(".proto") } + .map { descendant -> + val location = Location.get( + base = base, + path = descendant.relativeTo(rootDirectory).withUnixSlashes().toString(), + ) + ProtoFilePath(location, fileSystem, descendant) + } + .toSet() override fun resolve(import: String): ProtoFilePath? { val resolved = rootDirectory / import diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Rpc.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Rpc.kt index 7e90507dd2..55656f6658 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Rpc.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Rpc.kt @@ -75,35 +75,31 @@ data class Rpc( companion object { @JvmStatic - fun fromElements(elements: List): List { - return elements.map { element -> - Rpc( - location = element.location, - name = element.name, - documentation = element.documentation, - requestTypeElement = element.requestType, - responseTypeElement = element.responseType, - requestStreaming = element.requestStreaming, - responseStreaming = element.responseStreaming, - options = Options(Options.METHOD_OPTIONS, element.options), - ) - } + fun fromElements(elements: List): List = elements.map { element -> + Rpc( + location = element.location, + name = element.name, + documentation = element.documentation, + requestTypeElement = element.requestType, + responseTypeElement = element.responseType, + requestStreaming = element.requestStreaming, + responseStreaming = element.responseStreaming, + options = Options(Options.METHOD_OPTIONS, element.options), + ) } @JvmStatic - fun toElements(rpcs: List): List { - return rpcs.map { rpc -> - RpcElement( - location = rpc.location, - name = rpc.name, - documentation = rpc.documentation, - requestType = rpc.requestTypeElement, - responseType = rpc.responseTypeElement, - requestStreaming = rpc.requestStreaming, - responseStreaming = rpc.responseStreaming, - options = rpc.options.elements, - ) - } + fun toElements(rpcs: List): List = rpcs.map { rpc -> + RpcElement( + location = rpc.location, + name = rpc.name, + documentation = rpc.documentation, + requestType = rpc.requestTypeElement, + responseType = rpc.responseTypeElement, + requestStreaming = rpc.requestStreaming, + responseStreaming = rpc.responseStreaming, + options = rpc.options.elements, + ) } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Schema.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Schema.kt index 156f165d4c..abdda3ad70 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Schema.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Schema.kt @@ -83,17 +83,13 @@ class Schema internal constructor(protoFiles: Iterable) { * Returns the field with the fully qualified [typeName] and [memberName], or null if this schema * defines no such field. */ - fun getField(typeName: String, memberName: String): Field? { - return getField(ProtoType.get(typeName), memberName) - } + fun getField(typeName: String, memberName: String): Field? = getField(ProtoType.get(typeName), memberName) /** * Returns the field for [protoType] and [memberName], or null if this schema defines no such * field. */ - fun getField(protoType: ProtoType, memberName: String): Field? { - return getField(ProtoMember.get(protoType, memberName)) - } + fun getField(protoType: ProtoType, memberName: String): Field? = getField(ProtoMember.get(protoType, memberName)) /** * Returns a wire adapter for the message or enum type named [typeName]. The returned type diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaException.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaException.kt index e926e1430e..613d64cefe 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaException.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaException.kt @@ -15,6 +15,7 @@ */ package com.squareup.wire.schema -class SchemaException(errors: List) : RuntimeException( - errors.joinToString(separator = "\n"), -) +class SchemaException(errors: List) : + RuntimeException( + errors.joinToString(separator = "\n"), + ) diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHandler.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHandler.kt index ca742e694e..5bd6ea0eb8 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHandler.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHandler.kt @@ -112,14 +112,10 @@ abstract class SchemaHandler { val fullSchema: Schema, ) { /** True if this [protoFile] ia part of a `sourcePath` root. */ - fun inSourcePath(protoFile: ProtoFile): Boolean { - return inSourcePath(protoFile.location) - } + fun inSourcePath(protoFile: ProtoFile): Boolean = inSourcePath(protoFile.location) /** True if this [location] ia part of a `sourcePath` root. */ - fun inSourcePath(location: Location): Boolean { - return sourcePathPaths == null || location.path in sourcePathPaths - } + fun inSourcePath(location: Location): Boolean = sourcePathPaths == null || location.path in sourcePathPaths } /** diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt index a51158061b..e416e452d9 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt @@ -22,7 +22,9 @@ import okio.IOException * Load proto files and their transitive dependencies and parse them. Keep track of which files were * loaded from where so that we can use that information later when deciding what to generate. */ -expect class SchemaLoader(fileSystem: FileSystem) : Loader, ProfileLoader { +expect class SchemaLoader(fileSystem: FileSystem) : + Loader, + ProfileLoader { override fun load(path: String): ProtoFile /** Returns a new loader that reports failures to [errors]. */ diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaProtoAdapterFactory.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaProtoAdapterFactory.kt index 400bbc6534..3c8963a707 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaProtoAdapterFactory.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SchemaProtoAdapterFactory.kt @@ -133,17 +133,15 @@ internal class SchemaProtoAdapterFactory( private class EnumAdapter( private val enumType: EnumType, ) : ProtoAdapter(VARINT, Any::class, null, enumType.syntax) { - override fun encodedSize(value: Any): Int { - return when (value) { - is String -> { - INT32.encodedSize(enumType.constant(value)!!.tag) - } - is Int -> { - INT32.encodedSize(value) - } - else -> { - throw IllegalArgumentException("unexpected " + enumType.type + ": " + value) - } + override fun encodedSize(value: Any): Int = when (value) { + is String -> { + INT32.encodedSize(enumType.constant(value)!!.tag) + } + is Int -> { + INT32.encodedSize(value) + } + else -> { + throw IllegalArgumentException("unexpected " + enumType.type + ": " + value) } } @@ -181,9 +179,7 @@ internal class SchemaProtoAdapterFactory( return constant?.name ?: value } - override fun redact(value: Any): Any { - throw UnsupportedOperationException() - } + override fun redact(value: Any): Any = throw UnsupportedOperationException() } private class SchemaMessageBinding( diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt index 5270638a66..87d339381f 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Service.kt @@ -24,6 +24,7 @@ import com.squareup.wire.schema.internal.parser.ServiceElement import kotlin.jvm.JvmName import kotlin.jvm.JvmStatic +@Suppress("ktlint:standard:value-parameter-comment") data class Service( @get:JvmName("type") // For binary compatibility. val type: ProtoType, @@ -39,9 +40,7 @@ data class Service( val options: Options, ) { /** Returns the RPC named `name`, or null if this service has no such method. */ - fun rpc(name: String): Rpc? { - return rpcs.find { it.name == name } - } + fun rpc(name: String): Rpc? = rpcs.find { it.name == name } fun link(linker: Linker) { var linker = linker @@ -137,23 +136,19 @@ data class Service( @JvmStatic internal fun fromElements( packageName: String?, elements: List, - ): List { - return elements.map { service -> - val protoType = get(packageName, service.name) - fromElement(protoType, service) - } + ): List = elements.map { service -> + val protoType = get(packageName, service.name) + fromElement(protoType, service) } - @JvmStatic internal fun toElements(services: List): List { - return services.map { service -> - ServiceElement( - service.location, - service.name, - service.documentation, - Rpc.toElements(service.rpcs), - service.options.elements, - ) - } + @JvmStatic internal fun toElements(services: List): List = services.map { service -> + ServiceElement( + service.location, + service.name, + service.documentation, + Rpc.toElements(service.rpcs), + service.options.elements, + ) } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SyntaxRules.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SyntaxRules.kt index 21160b5902..2079974cb8 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SyntaxRules.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/SyntaxRules.kt @@ -38,13 +38,11 @@ interface SyntaxRules { fun jsonName(name: String, declaredJsonName: String?): String companion object { - fun get(syntax: Syntax?): SyntaxRules { - return when (syntax) { - PROTO_3 -> PROTO_3_SYNTAX_RULES - PROTO_2, - null, - -> PROTO_2_SYNTAX_RULES - } + fun get(syntax: Syntax?): SyntaxRules = when (syntax) { + PROTO_3 -> PROTO_3_SYNTAX_RULES + PROTO_2, + null, + -> PROTO_2_SYNTAX_RULES } internal val PROTO_2_SYNTAX_RULES = object : SyntaxRules { @@ -72,25 +70,21 @@ interface SyntaxRules { label: Field.Label?, isPacked: Boolean, isOneOf: Boolean, - ): Field.EncodeMode { - return when (label) { - Field.Label.REPEATED -> - if (isPacked) { - Field.EncodeMode.PACKED - } else { - Field.EncodeMode.REPEATED - } - Field.Label.OPTIONAL -> Field.EncodeMode.NULL_IF_ABSENT - Field.Label.REQUIRED -> Field.EncodeMode.REQUIRED - Field.Label.ONE_OF, - null, - -> if (protoType.isMap) Field.EncodeMode.MAP else Field.EncodeMode.NULL_IF_ABSENT - } + ): Field.EncodeMode = when (label) { + Field.Label.REPEATED -> + if (isPacked) { + Field.EncodeMode.PACKED + } else { + Field.EncodeMode.REPEATED + } + Field.Label.OPTIONAL -> Field.EncodeMode.NULL_IF_ABSENT + Field.Label.REQUIRED -> Field.EncodeMode.REQUIRED + Field.Label.ONE_OF, + null, + -> if (protoType.isMap) Field.EncodeMode.MAP else Field.EncodeMode.NULL_IF_ABSENT } - override fun jsonName(name: String, declaredJsonName: String?): String { - return declaredJsonName ?: name - } + override fun jsonName(name: String, declaredJsonName: String?): String = declaredJsonName ?: name } internal val PROTO_3_SYNTAX_RULES = object : SyntaxRules { @@ -123,9 +117,7 @@ interface SyntaxRules { override fun isPackedByDefault( type: ProtoType, label: Field.Label?, - ): Boolean { - return label == Field.Label.REPEATED && type in ProtoType.NUMERIC_SCALAR_TYPES - } + ): Boolean = label == Field.Label.REPEATED && type in ProtoType.NUMERIC_SCALAR_TYPES override fun getEncodeMode( protoType: ProtoType, @@ -147,9 +139,7 @@ interface SyntaxRules { return Field.EncodeMode.OMIT_IDENTITY } - override fun jsonName(name: String, declaredJsonName: String?): String { - return declaredJsonName ?: camelCase(name) - } + override fun jsonName(name: String, declaredJsonName: String?): String = declaredJsonName ?: camelCase(name) } } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Type.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Type.kt index 63e879b88b..dc0958a727 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Type.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/Type.kt @@ -60,12 +60,10 @@ sealed class Type { } companion object { - fun get(namespaces: List, protoType: ProtoType, type: TypeElement, syntax: Syntax): Type { - return when (type) { - is EnumElement -> fromElement(protoType, type, syntax) - is MessageElement -> fromElement(namespaces, protoType, type, syntax) - else -> throw IllegalArgumentException("unexpected type: $type") - } + fun get(namespaces: List, protoType: ProtoType, type: TypeElement, syntax: Syntax): Type = when (type) { + is EnumElement -> fromElement(protoType, type, syntax) + is MessageElement -> fromElement(namespaces, protoType, type, syntax) + else -> throw IllegalArgumentException("unexpected type: $type") } @JvmStatic @@ -82,12 +80,10 @@ sealed class Type { return@map get(namespaces, protoType, it, syntax) } - private fun toElement(type: Type): TypeElement { - return when (type) { - is EnumType -> type.toElement() - is MessageType -> type.toElement() - is EnclosingType -> type.toElement() - } + private fun toElement(type: Type): TypeElement = when (type) { + is EnumType -> type.toElement() + is MessageType -> type.toElement() + is EnclosingType -> type.toElement() } @JvmStatic diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/WireRun.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/WireRun.kt index a7b75871ab..e579e0f92d 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/WireRun.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/WireRun.kt @@ -236,9 +236,7 @@ class WireRun( } } - fun execute(fs: FileSystem, logger: WireLogger) { - return execute(fs, logger, SchemaLoader(fs)) - } + fun execute(fs: FileSystem, logger: WireLogger) = execute(fs, logger, SchemaLoader(fs)) internal fun execute(fs: FileSystem, logger: WireLogger, schemaLoader: SchemaLoader) { eventListeners.forEach { it.runStart(wireRun = this) } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/CommonSchemaLoader.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/CommonSchemaLoader.kt index 8d9e82ea5d..6de3ba6ca3 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/CommonSchemaLoader.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/CommonSchemaLoader.kt @@ -38,7 +38,9 @@ import okio.IOException * Load proto files and their transitive dependencies and parse them. Keep track of which files were * loaded from where so that we can use that information later when deciding what to generate. */ -internal class CommonSchemaLoader : Loader, ProfileLoader { +internal class CommonSchemaLoader : + Loader, + ProfileLoader { private val fileSystem: FileSystem /** Errors accumulated by this load. */ @@ -273,11 +275,9 @@ internal class CommonSchemaLoader : Loader, ProfileLoader { } } -internal fun ProtoFile.importPath(location: Location): String { - return when { - location.base.isEmpty() -> canonicalImportPath(location) - else -> location.path - } +internal fun ProtoFile.importPath(location: Location): String = when { + location.base.isEmpty() -> canonicalImportPath(location) + else -> location.path } internal fun ProtoFile.canonicalImportPath(location: Location): String { diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/SchemaEncoder.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/SchemaEncoder.kt index 5332744f53..f14575a112 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/SchemaEncoder.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/SchemaEncoder.kt @@ -74,9 +74,7 @@ class SchemaEncoder( private val rpcOptionsProtoAdapter = schema.protoAdapter(Options.METHOD_OPTIONS.toString(), false) - fun encode(protoFile: ProtoFile): ByteString { - return fileEncoder.encode(protoFile).toByteString() - } + fun encode(protoFile: ProtoFile): ByteString = fileEncoder.encode(protoFile).toByteString() private val fileEncoder: Encoder = object : Encoder() { override fun encode(writer: ReverseProtoWriter, value: ProtoFile) { @@ -410,12 +408,13 @@ class SchemaEncoder( } /** Encodes a synthetic map type. */ - private abstract class Encoder : ProtoAdapter( - FieldEncoding.LENGTH_DELIMITED, - null, - null, - Syntax.PROTO_2, - ) { + private abstract class Encoder : + ProtoAdapter( + FieldEncoding.LENGTH_DELIMITED, + null, + null, + Syntax.PROTO_2, + ) { override fun redact(value: T) = value override fun encodedSize(value: T): Int = throw UnsupportedOperationException() override fun encode(writer: ProtoWriter, value: T) = throw UnsupportedOperationException() @@ -441,11 +440,9 @@ class SchemaEncoder( return result } - private fun toJson(field: Field, value: Any): Any { - return when { - field.isRepeated -> (value as List<*>).map { toJsonSingle(field.type!!, it!!) } - else -> toJsonSingle(field.type!!, value) - } + private fun toJson(field: Field, value: Any): Any = when { + field.isRepeated -> (value as List<*>).map { toJsonSingle(field.type!!, it!!) } + else -> toJsonSingle(field.type!!, value) } /** diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/TypeMover.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/TypeMover.kt index a21d0b6885..2bce1172d1 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/TypeMover.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/TypeMover.kt @@ -163,9 +163,7 @@ class TypeMover( } /** Returns the type that moved. */ - private fun getType(move: Move): Type { - return pathToFile[move.targetPath]!!.types.first { it.type == move.type } - } + private fun getType(move: Move): Type = pathToFile[move.targetPath]!!.types.first { it.type == move.type } private fun ProtoFile.collectReferencedTypes(sink: MutableSet) { for (type in types) { @@ -215,16 +213,14 @@ class TypeMover( } } - private fun ProtoFile.emptyCopy(path: String): ProtoFile { - return copy( - location = location.copy(path = path), - imports = listOf(), - publicImports = listOf(), - types = listOf(), - services = listOf(), - extendList = listOf(), - ) - } + private fun ProtoFile.emptyCopy(path: String): ProtoFile = copy( + location = location.copy(path = path), + imports = listOf(), + publicImports = listOf(), + types = listOf(), + services = listOf(), + extendList = listOf(), + ) private fun checkForErrors() { require(errors.isEmpty()) { errors.joinToString(separator = "\n") } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/Util.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/Util.kt index 4347858347..ec0fe9f4f6 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/Util.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/Util.kt @@ -85,9 +85,8 @@ private const val RESERVED_TAG_VALUE_START = 19000 private const val RESERVED_TAG_VALUE_END = 19999 /** True if the supplied value is in the valid tag range and not reserved. */ -internal fun Int.isValidTag() = - this in MIN_TAG_VALUE until RESERVED_TAG_VALUE_START || - this in (RESERVED_TAG_VALUE_END + 1) until MAX_TAG_VALUE + 1 +internal fun Int.isValidTag() = this in MIN_TAG_VALUE until RESERVED_TAG_VALUE_START || + this in (RESERVED_TAG_VALUE_END + 1) until MAX_TAG_VALUE + 1 internal expect fun Char.isDigit(): Boolean @@ -154,6 +153,4 @@ private fun Service.asStub() = copy( options = Options(Options.SERVICE_OPTIONS, emptyList()), ) -fun Path.withUnixSlashes(): Path { - return toString().replace('\\', '/').toPath() -} +fun Path.withUnixSlashes(): Path = toString().replace('\\', '/').toPath() diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/FieldElement.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/FieldElement.kt index 006e2b3cc6..9a06c468e1 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/FieldElement.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/FieldElement.kt @@ -74,25 +74,23 @@ data class FieldElement( } // Only non-repeated scalar types and Enums support default values. - private fun ProtoType.toKind(): OptionElement.Kind { - return when (simpleName) { - "bool" -> OptionElement.Kind.BOOLEAN - "string" -> OptionElement.Kind.STRING - "bytes", - "double", - "float", - "fixed32", - "fixed64", - "int32", - "int64", - "sfixed32", - "sfixed64", - "sint32", - "sint64", - "uint32", - "uint64", - -> OptionElement.Kind.NUMBER - else -> OptionElement.Kind.ENUM - } + private fun ProtoType.toKind(): OptionElement.Kind = when (simpleName) { + "bool" -> OptionElement.Kind.BOOLEAN + "string" -> OptionElement.Kind.STRING + "bytes", + "double", + "float", + "fixed32", + "fixed64", + "int32", + "int64", + "sfixed32", + "sfixed64", + "sint32", + "sint64", + "uint32", + "uint64", + -> OptionElement.Kind.NUMBER + else -> OptionElement.Kind.ENUM } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoFileElement.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoFileElement.kt index c6710d4736..20cad06bfd 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoFileElement.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoFileElement.kt @@ -85,8 +85,6 @@ data class ProtoFileElement( companion object { /** Returns an empty proto file to serve as a null object when a file cannot be found. */ @JvmStatic - fun empty(path: String): ProtoFileElement { - return ProtoFileElement(location = Location.get(path)) - } + fun empty(path: String): ProtoFileElement = ProtoFileElement(location = Location.get(path)) } } diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoParser.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoParser.kt index fc92e7202d..b4495d91f5 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoParser.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/ProtoParser.kt @@ -394,14 +394,10 @@ class ProtoParser internal constructor( } /** Defaults aren't options. */ - private fun stripDefault(options: MutableList): String? { - return stripValue("default", options) - } + private fun stripDefault(options: MutableList): String? = stripValue("default", options) /** `json_name` isn't an option. */ - private fun stripJsonName(options: MutableList): String? { - return stripValue("json_name", options) - } + private fun stripJsonName(options: MutableList): String? = stripValue("json_name", options) /** * This finds an option named [name], removes, and returns it. diff --git a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/SyntaxReader.kt b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/SyntaxReader.kt index 0d71cd6eb0..db6da39849 100644 --- a/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/SyntaxReader.kt +++ b/wire-schema/src/commonMain/kotlin/com/squareup/wire/schema/internal/parser/SyntaxReader.kt @@ -53,14 +53,12 @@ class SyntaxReader( } /** Note that although the name suggests otherwise, this does consume the char if it finds it. */ - fun peekChar(c: Char): Boolean { - return when (peekChar()) { - c -> { - pos++ - true - } - else -> false + fun peekChar(c: Char): Boolean = when (peekChar()) { + c -> { + pos++ + true } + else -> false } /** Push back the most recently read character. */ @@ -132,13 +130,11 @@ class SyntaxReader( return value.toChar() } - private fun hexDigit(c: Char): Int { - return when (c) { - in '0'..'9' -> c - '0' - in 'a'..'f' -> c - 'a' + 10 - in 'A'..'F' -> c - 'A' + 10 - else -> -1 - } + private fun hexDigit(c: Char): Int = when (c) { + in '0'..'9' -> c - '0' + in 'a'..'f' -> c - 'a' + 10 + in 'A'..'F' -> c - 'A' + 10 + else -> -1 } /** @@ -147,26 +143,24 @@ class SyntaxReader( * or square brackets, the returned string retains the wrapping * punctuation. Otherwise, just the symbol is returned. */ - fun readName(allowLeadingDigit: Boolean = true, retainWrap: Boolean = false): String { - return when (peekChar()) { - '(' -> { - pos++ - val word = readWord(allowLeadingDigit).also { - expect(readChar() == ')') { "expected ')'" } - } - if (retainWrap) "($word)" else word + fun readName(allowLeadingDigit: Boolean = true, retainWrap: Boolean = false): String = when (peekChar()) { + '(' -> { + pos++ + val word = readWord(allowLeadingDigit).also { + expect(readChar() == ')') { "expected ')'" } } + if (retainWrap) "($word)" else word + } - '[' -> { - pos++ - val word = readWord(allowLeadingDigit).also { - expect(readChar() == ']') { "expected ']'" } - } - if (retainWrap) "[$word]" else word + '[' -> { + pos++ + val word = readWord(allowLeadingDigit).also { + expect(readChar() == ']') { "expected ']'" } } - - else -> readWord(allowLeadingDigit) + if (retainWrap) "[$word]" else word } + + else -> readWord(allowLeadingDigit) } /** Reads a scalar, map, or type name. */ @@ -176,26 +170,24 @@ class SyntaxReader( } /** Reads a scalar, map, or type name with `name` as a prefix word. */ - fun readDataType(name: String): String { - return when (name) { - "map" -> { - expect(readChar() == '<') { "expected '<'" } - val keyType = readDataType() + fun readDataType(name: String): String = when (name) { + "map" -> { + expect(readChar() == '<') { "expected '<'" } + val keyType = readDataType() - expect(readChar() == ',') { "expected ','" } - val valueType = readDataType() + expect(readChar() == ',') { "expected ','" } + val valueType = readDataType() - expect(readChar() == '>') { "expected '>'" } - "map<$keyType, $valueType>" - } + expect(readChar() == '>') { "expected '>'" } + "map<$keyType, $valueType>" + } - else -> { - buildString { - append(name) - while (peekChar() == '.') { - pos++ // We skip the dot so we can read the next word. - append(".${readWord()}") - } + else -> { + buildString { + append(name) + while (peekChar() == '.') { + pos++ // We skip the dot so we can read the next word. + append(".${readWord()}") } } } diff --git a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/Assertions.kt b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/Assertions.kt index 8c136ff0c6..fc0c58f3b4 100644 --- a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/Assertions.kt +++ b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/Assertions.kt @@ -19,6 +19,4 @@ import assertk.Assert import assertk.assertions.containsExactly /** This doesn't exist in AssertK right now. See https://github.com/willowtreeapps/assertk/discussions/489 */ -internal inline fun Assert>.containsExactly(vararg expected: T) { - return transform { it.toList() }.containsExactly(*expected) -} +internal inline fun Assert>.containsExactly(vararg expected: T) = transform { it.toList() }.containsExactly(*expected) diff --git a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/DagCheckerTest.kt b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/DagCheckerTest.kt index b3dc7b6ebd..e4c6a59333 100644 --- a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/DagCheckerTest.kt +++ b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/DagCheckerTest.kt @@ -142,8 +142,6 @@ class DagCheckerTest { assertThat(cycleFinder.check()).containsExactly(listOf("a", "d", "e", "b", "f", "i", "h")) } - private fun String.targets(allEdges: List): List { - return allEdges.filter { it.startsWith(this) } - .map { it.substring(1) } - } + private fun String.targets(allEdges: List): List = allEdges.filter { it.startsWith(this) } + .map { it.substring(1) } } diff --git a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/parser/ProtoParserTest.kt b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/parser/ProtoParserTest.kt index b645fae322..f40835bb39 100644 --- a/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/parser/ProtoParserTest.kt +++ b/wire-schema/src/commonTest/kotlin/com/squareup/wire/schema/internal/parser/ProtoParserTest.kt @@ -2003,6 +2003,7 @@ class ProtoParserTest { } @Test + @Suppress("ktlint:standard:property-naming") fun structuredOption() { val proto = """ |message ExoticOptions { diff --git a/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/Multimap.kt b/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/Multimap.kt index 522e874490..2b82fbe91d 100644 --- a/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/Multimap.kt +++ b/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/Multimap.kt @@ -35,6 +35,4 @@ private class SimpleMultimap(private val map: Map>) : Mul override fun asMap() = map } -internal actual fun Map>.toMultimap(): Multimap { - return SimpleMultimap(this) -} +internal actual fun Map>.toMultimap(): Multimap = SimpleMultimap(this) diff --git a/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt b/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt index a9485c65b6..c9bf3537b5 100644 --- a/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt +++ b/wire-schema/src/jsMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt @@ -18,7 +18,9 @@ package com.squareup.wire.schema import com.squareup.wire.schema.internal.CommonSchemaLoader import okio.FileSystem -actual class SchemaLoader : Loader, ProfileLoader { +actual class SchemaLoader : + Loader, + ProfileLoader { private val delegate: CommonSchemaLoader actual constructor(fileSystem: FileSystem) { diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/EventListeners.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/EventListeners.kt index a27eea5d3a..9ccee73453 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/EventListeners.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/EventListeners.kt @@ -21,9 +21,7 @@ package com.squareup.wire.schema * @param eventListenerFactoryClass a fully qualified class name for a class that implements [EventListener.Factory]. The * class must have a no-arguments public constructor. */ -fun newEventListenerFactory(eventListenerFactoryClass: String): EventListener.Factory { - return ClassNameEventListenerFactory(eventListenerFactoryClass) -} +fun newEventListenerFactory(eventListenerFactoryClass: String): EventListener.Factory = ClassNameEventListenerFactory(eventListenerFactoryClass) /** * This event listener factory is serializable (so Gradle can cache targets that use it). It works @@ -58,7 +56,5 @@ private class ClassNameEventListenerFactory( return result } - override fun create(): EventListener { - return delegate.create() - } + override fun create(): EventListener = delegate.create() } diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/Profile.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/Profile.kt index fff57bd10b..45adb0a7e1 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/Profile.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/Profile.kt @@ -44,8 +44,7 @@ actual class Profile actual constructor( } /** Returns the config for [type], or null if it is not configured. */ - private fun typeConfig(type: ProtoType) = - profileFiles - .flatMap { it.typeConfigs } - .find { it.type == type.toString() } + private fun typeConfig(type: ProtoType) = profileFiles + .flatMap { it.typeConfigs } + .find { it.type == type.toString() } } diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt index 82604a9c71..76ba9a5a57 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt @@ -20,7 +20,9 @@ import java.nio.file.FileSystem as NioFileSystem import okio.FileSystem import okio.FileSystem.Companion.asOkioFileSystem -actual class SchemaLoader : Loader, ProfileLoader { +actual class SchemaLoader : + Loader, + ProfileLoader { private val delegate: CommonSchemaLoader constructor(fileSystem: NioFileSystem) : this(fileSystem.asOkioFileSystem()) diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/WireLoggers.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/WireLoggers.kt index 9b7d584a20..1bb31ff3f5 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/WireLoggers.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/WireLoggers.kt @@ -24,14 +24,10 @@ import okio.Path * @param loggerFactoryClass a fully qualified class name for a class that implements [WireLogger.Factory]. The * class must have a no-arguments public constructor. */ -fun newLoggerFactory(loggerFactoryClass: String): WireLogger.Factory { - return ClassNameLoggerFactory(loggerFactoryClass) -} +fun newLoggerFactory(loggerFactoryClass: String): WireLogger.Factory = ClassNameLoggerFactory(loggerFactoryClass) class EmptyWireLoggerFactory : WireLogger.Factory { - override fun create(): WireLogger { - return EmptyWireLogger() - } + override fun create(): WireLogger = EmptyWireLogger() } class EmptyWireLogger : WireLogger { @@ -81,7 +77,5 @@ private class ClassNameLoggerFactory( return result } - override fun create(): WireLogger { - return delegate.create() - } + override fun create(): WireLogger = delegate.create() } diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/JvmLanguages.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/JvmLanguages.kt index 15fb43c0d8..e62e1abc36 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/JvmLanguages.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/JvmLanguages.kt @@ -106,20 +106,22 @@ fun eligibleAsAnnotationMember(schema: Schema, field: Field): Boolean { return true } -fun annotationTargetType(extend: Extend): ElementType? { - return when (extend.type!!) { - Options.MESSAGE_OPTIONS, Options.ENUM_OPTIONS, Options.SERVICE_OPTIONS -> ElementType.TYPE - Options.FIELD_OPTIONS, Options.ENUM_VALUE_OPTIONS -> ElementType.FIELD - Options.METHOD_OPTIONS -> ElementType.METHOD - else -> null - } +fun annotationTargetType(extend: Extend): ElementType? = when (extend.type!!) { + Options.MESSAGE_OPTIONS, Options.ENUM_OPTIONS, Options.SERVICE_OPTIONS -> ElementType.TYPE + Options.FIELD_OPTIONS, Options.ENUM_VALUE_OPTIONS -> ElementType.FIELD + Options.METHOD_OPTIONS -> ElementType.METHOD + else -> null } fun optionValueToInt(value: Any?): Int { if (value == null) return 0 val string = value.toString() - val negativeSign = if (string.startsWith('-')) { "-" } else { "" } + val negativeSign = if (string.startsWith('-')) { + "-" + } else { + "" + } return when { // Hexadecimal. @@ -141,7 +143,11 @@ fun optionValueToLong(value: Any?): Long { if (value == null) return 0L val string = value.toString() - val negativeSign = if (string.startsWith('-')) { "-" } else { "" } + val negativeSign = if (string.startsWith('-')) { + "-" + } else { + "" + } return when { // Hexadecimal. diff --git a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/fileSystems.kt b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/fileSystems.kt index 7356a2d88f..ee31a38781 100644 --- a/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/fileSystems.kt +++ b/wire-schema/src/jvmMain/kotlin/com/squareup/wire/schema/internal/fileSystems.kt @@ -27,14 +27,12 @@ private val UNICODE_BOMS = okio.Options.of( "0000feff".decodeHex(), // UTF-32BE ) -internal fun BufferedSource.readBomAsCharset(default: Charset = Charsets.UTF_8): Charset { - return when (select(UNICODE_BOMS)) { - 0 -> Charsets.UTF_8 - 1 -> Charsets.UTF_16BE - 2 -> Charsets.UTF_32LE - 3 -> Charsets.UTF_16LE - 4 -> Charsets.UTF_32BE - -1 -> default - else -> throw AssertionError() - } +internal fun BufferedSource.readBomAsCharset(default: Charset = Charsets.UTF_8): Charset = when (select(UNICODE_BOMS)) { + 0 -> Charsets.UTF_8 + 1 -> Charsets.UTF_16BE + 2 -> Charsets.UTF_32LE + 3 -> Charsets.UTF_16LE + 4 -> Charsets.UTF_32BE + -1 -> default + else -> throw AssertionError() } diff --git a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/ManifestPartitionTest.kt b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/ManifestPartitionTest.kt index 4edc75cae1..e31766d9de 100644 --- a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/ManifestPartitionTest.kt +++ b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/ManifestPartitionTest.kt @@ -179,8 +179,6 @@ class ManifestPartitionTest { } } -private fun Schema.getMessage(name: String): MessageType { - return checkNotNull(getType(name) as? MessageType) { - "No type '$name' in schema" - } +private fun Schema.getMessage(name: String): MessageType = checkNotNull(getType(name) as? MessageType) { + "No type '$name' in schema" } diff --git a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/PrunerTest.kt b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/PrunerTest.kt index 549c16a3c2..c96b3b3b2f 100644 --- a/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/PrunerTest.kt +++ b/wire-schema/src/jvmTest/kotlin/com/squareup/wire/schema/PrunerTest.kt @@ -4097,4 +4097,5 @@ class PrunerTest { } // Used so that spotless or the IDE doesn't trim them away. +@Suppress("ktlint:standard:property-naming") private const val space = " " diff --git a/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/Multimap.kt b/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/Multimap.kt index b75ea48a05..b23c3d2c2a 100644 --- a/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/Multimap.kt +++ b/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/Multimap.kt @@ -35,6 +35,4 @@ private class SimpleMultimap(private val map: Map>) : Mul override fun asMap() = map } -internal actual fun Map>.toMultimap(): Multimap { - return SimpleMultimap(this) -} +internal actual fun Map>.toMultimap(): Multimap = SimpleMultimap(this) diff --git a/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt b/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt index a9485c65b6..c9bf3537b5 100644 --- a/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt +++ b/wire-schema/src/nativeMain/kotlin/com/squareup/wire/schema/SchemaLoader.kt @@ -18,7 +18,9 @@ package com.squareup.wire.schema import com.squareup.wire.schema.internal.CommonSchemaLoader import okio.FileSystem -actual class SchemaLoader : Loader, ProfileLoader { +actual class SchemaLoader : + Loader, + ProfileLoader { private val delegate: CommonSchemaLoader actual constructor(fileSystem: FileSystem) { diff --git a/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt b/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt index c9494df70f..5c6d62843b 100644 --- a/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt +++ b/wire-swift-generator/src/main/java/com/squareup/wire/swift/SwiftGenerator.kt @@ -281,14 +281,12 @@ class SwiftGenerator private constructor( else -> error("Unknown type $type") } - private fun String.sanitizeDoc(): String { - return this - // Remove trailing whitespace on each line. - .replace("[^\\S\n]+\n".toRegex(), "\n") - .replace("\\s+$".toRegex(), "") - .replace("\\*/".toRegex(), "*/") - .replace("/\\*".toRegex(), "/*") - } + private fun String.sanitizeDoc(): String = this + // Remove trailing whitespace on each line. + .replace("[^\\S\n]+\n".toRegex(), "\n") + .replace("\\s+$".toRegex(), "") + .replace("\\*/".toRegex(), "*/") + .replace("/\\*".toRegex(), "/*") /** * Returns true if [field] inside [type] forms a cycle and needs an indirection to allow it @@ -694,7 +692,11 @@ class SwiftGenerator private constructor( } } - val fieldName = if (hasPropertyWrapper) { "_${field.safeName}" } else { field.safeName } + val fieldName = if (hasPropertyWrapper) { + "_${field.safeName}" + } else { + field.safeName + } addStatement( if (hasPropertyWrapper) { "self.%N.wrappedValue = %L" @@ -780,85 +782,182 @@ class SwiftGenerator private constructor( structType: DeclaredTypeName, storageName: String, storageType: DeclaredTypeName, - ): ExtensionSpec { - return ExtensionSpec.builder(structType) - .addSuperType(codable) - .apply { - addFunction( - FunctionSpec.constructorBuilder() - .addParameter("from", "decoder", decoder) + ): ExtensionSpec = ExtensionSpec.builder(structType) + .addSuperType(codable) + .apply { + addFunction( + FunctionSpec.constructorBuilder() + .addParameter("from", "decoder", decoder) + .addModifiers(PUBLIC) + .throws(true) + .addStatement("let container = try decoder.singleValueContainer()") + .addStatement("self.%N = try container.decode(%T.self)", storageName, storageType) + .build(), + ) + addFunction( + FunctionSpec.builder("encode") + .addParameter("to", "encoder", encoder) + .addModifiers(PUBLIC) + .throws(true) + .addStatement("var container = encoder.singleValueContainer()") + .addStatement("try container.encode(%N)", storageName) + .build(), + ) + } + .build() + + private fun messageCodableExtension( + type: MessageType, + structType: DeclaredTypeName, + ): ExtensionSpec = ExtensionSpec.builder(structType) + .addSuperType(codable) + .apply { + val codingKeys = if (type.declaredFieldsAndOneOfFields.isEmpty()) { + structType.nestedType("CodingKeys") + } else { + stringLiteralCodingKeys + } + + if (type.declaredFieldsAndOneOfFields.isEmpty()) { + addType( + // Coding keys still need to be specified on empty messages in order to prevent `unknownFields` from + // getting serialized via JSON/Codable. In this case, the keys cannot conform to `RawRepresentable` + // in order to compile. + + TypeSpec.enumBuilder(codingKeys) .addModifiers(PUBLIC) - .throws(true) - .addStatement("let container = try decoder.singleValueContainer()") - .addStatement("self.%N = try container.decode(%T.self)", storageName, storageType) + .addSuperType(codingKey) .build(), ) + } + + // We cannot rely upon built-in Codable support since we need to support multiple keys. + if (type.declaredFieldsAndOneOfFields.isNotEmpty()) { + // check for name collisions + val container = if ("container" in type.declaredFieldsAndOneOfFields.map { it.name }) "_container" else "container" + addFunction( - FunctionSpec.builder("encode") - .addParameter("to", "encoder", encoder) + FunctionSpec.constructorBuilder() + .addParameter("from", "decoder", decoder) .addModifiers(PUBLIC) .throws(true) - .addStatement("var container = encoder.singleValueContainer()") - .addStatement("try container.encode(%N)", storageName) - .build(), - ) - } - .build() - } + .addStatement("let $container = try decoder.container(keyedBy: %T.self)", codingKeys) + .apply { + type.declaredFields.forEach { field -> + val hasPropertyWrapper = !isIndirect(type, field) && (field.defaultedValue != null || field.isProtoDefaulted) - private fun messageCodableExtension( - type: MessageType, - structType: DeclaredTypeName, - ): ExtensionSpec { - return ExtensionSpec.builder(structType) - .addSuperType(codable) - .apply { - val codingKeys = if (type.declaredFieldsAndOneOfFields.isEmpty()) { - structType.nestedType("CodingKeys") - } else { - stringLiteralCodingKeys - } + var typeName: TypeName = field.typeName.makeNonOptional() + if (field.isRepeated && typeName is ParameterizedTypeName) { + typeName = typeName.typeArguments[0] + } - if (type.declaredFieldsAndOneOfFields.isEmpty()) { - addType( - // Coding keys still need to be specified on empty messages in order to prevent `unknownFields` from - // getting serialized via JSON/Codable. In this case, the keys cannot conform to `RawRepresentable` - // in order to compile. + var decode = "decode" + if (field.isRepeated) { + decode += "ProtoArray" + } else if (field.isMap) { + decode += "ProtoMap" + } else if (field.isOptional) { + decode += "IfPresent" + } - TypeSpec.enumBuilder(codingKeys) - .addModifiers(PUBLIC) - .addSuperType(codingKey) - .build(), - ) - } + val typeArg = if (field.typeName.isStringEncoded) { + "stringEncoded: " + } else { + "" + } - // We cannot rely upon built-in Codable support since we need to support multiple keys. - if (type.declaredFieldsAndOneOfFields.isNotEmpty()) { - // check for name collisions - val container = if ("container" in type.declaredFieldsAndOneOfFields.map { it.name }) "_container" else "container" + val forKeys = field.codableName?.let { + "firstOfKeys" + } ?: "forKey" - addFunction( - FunctionSpec.constructorBuilder() - .addParameter("from", "decoder", decoder) - .addModifiers(PUBLIC) - .throws(true) - .addStatement("let $container = try decoder.container(keyedBy: %T.self)", codingKeys) - .apply { - type.declaredFields.forEach { field -> - val hasPropertyWrapper = !isIndirect(type, field) && (field.defaultedValue != null || field.isProtoDefaulted) + val keys = listOf(field.codableName, field.name) + .filterNotNull() + .map { CodeBlock.of("%S", it) } + .joinToCode() + + val fieldName = if (hasPropertyWrapper) { + "_${field.safeName}" + } else { + field.safeName + } + val prefix = if (hasPropertyWrapper) { + "self.%1N.wrappedValue" + } else { + "self.%1N" + } + addStatement( + "$prefix = try $container.$decode($typeArg%2T.self, $forKeys: $keys)", + fieldName, + typeName, + ) + } - var typeName: TypeName = field.typeName.makeNonOptional() - if (field.isRepeated && typeName is ParameterizedTypeName) { - typeName = typeName.typeArguments[0] + type.oneOfs.forEach { oneOf -> + oneOf.fields.fold(mutableListOf>()) { memo, field -> + field.codableName?.let { codableName -> + memo.add(Pair(field, codableName)) + } + memo.add(Pair(field, field.name)) + + memo + }.forEachIndexed { index, pair -> + val (field, keyName) = pair + + val typeName = field.typeName.makeNonOptional() + + val safeName = field.safeName + val fieldName = if (safeName == "self") "self_" else safeName + + if (index == 0) { + beginControlFlow( + "if", + "let %1N = try $container.decodeIfPresent(%2T.self, forKey: %3S)", + fieldName, + typeName, + keyName, + ) + } else { + nextControlFlow( + "else if", + "let %1N = try $container.decodeIfPresent(%2T.self, forKey: %3S)", + fieldName, + typeName, + keyName, + ) } + addStatement("self.%1N = .%2N(%3N)", oneOf.name, field.safeName, fieldName) + } + nextControlFlow("else", "") + addStatement("self.%N = nil", oneOf.name) + endControlFlow("if") + } + } + .build(), + ) + addFunction( + FunctionSpec.builder("encode") + .addParameter("to", "encoder", encoder) + .addModifiers(PUBLIC) + .throws(true) + .addStatement("var $container = encoder.container(keyedBy: %T.self)", codingKeys) + .apply { + if (type.declaredFieldsAndOneOfFields.any { it.codableName != null }) { + addStatement("let preferCamelCase = encoder.protoKeyNameEncodingStrategy == .camelCase") + } + if (type.declaredFields.any { !it.isOptional && (it.isCollection || it.isEnum || it.codableDefaultValue != null) }) { + addStatement("let includeDefaults = encoder.protoDefaultValuesEncodingStrategy == .include") + } + addStatement("") - var decode = "decode" + type.declaredFields.forEach { field -> + fun addEncode() { + var encode = "encode" if (field.isRepeated) { - decode += "ProtoArray" + encode += "ProtoArray" } else if (field.isMap) { - decode += "ProtoMap" + encode += "ProtoMap" } else if (field.isOptional) { - decode += "IfPresent" + encode += "IfPresent" } val typeArg = if (field.typeName.isStringEncoded) { @@ -867,164 +966,71 @@ class SwiftGenerator private constructor( "" } - val forKeys = field.codableName?.let { - "firstOfKeys" - } ?: "forKey" - - val keys = listOf(field.codableName, field.name) - .filterNotNull() - .map { CodeBlock.of("%S", it) } - .joinToCode() + val (keys, args) = field.codableName?.let { codableName -> + Pair( + "preferCamelCase ? %3S : %2S", + arrayOf(field.name, codableName), + ) + } ?: Pair("%2S", arrayOf(field.name)) - val fieldName = if (hasPropertyWrapper) { "_${field.safeName}" } else { field.safeName } - val prefix = if (hasPropertyWrapper) { "self.%1N.wrappedValue" } else { "self.%1N" } addStatement( - "$prefix = try $container.$decode($typeArg%2T.self, $forKeys: $keys)", - fieldName, - typeName, + "try $container.$encode(${typeArg}self.%1N, forKey: $keys)", + field.safeName, + *args, ) } - type.oneOfs.forEach { oneOf -> - oneOf.fields.fold(mutableListOf>()) { memo, field -> - field.codableName?.let { codableName -> - memo.add(Pair(field, codableName)) - } - memo.add(Pair(field, field.name)) - - memo - }.forEachIndexed { index, pair -> - val (field, keyName) = pair - - val typeName = field.typeName.makeNonOptional() - - val safeName = field.safeName - val fieldName = if (safeName == "self") "self_" else safeName - - if (index == 0) { - beginControlFlow( - "if", - "let %1N = try $container.decodeIfPresent(%2T.self, forKey: %3S)", - fieldName, - typeName, - keyName, - ) - } else { - nextControlFlow( - "else if", - "let %1N = try $container.decodeIfPresent(%2T.self, forKey: %3S)", - fieldName, - typeName, - keyName, - ) - } - addStatement("self.%1N = .%2N(%3N)", oneOf.name, field.safeName, fieldName) - } - nextControlFlow("else", "") - addStatement("self.%N = nil", oneOf.name) + val defaultValue = field.codableDefaultValue + + if (field.isOptional) { + // A proto3 field that is defined with the optional keyword supports field presence. + // Fields that have a value set and that support field presence always include the field value + // in the JSON-encoded output, even if it is the default value. + addEncode() + } else if (field.isCollection) { + beginControlFlow("if", "includeDefaults || !self.%N.isEmpty", field.safeName) + addEncode() + endControlFlow("if") + } else if (field.isEnum) { + beginControlFlow("if", "includeDefaults || self.%N.rawValue != 0", field.safeName) + addEncode() + endControlFlow("if") + } else if (defaultValue != null) { + beginControlFlow("if", "includeDefaults || self.%N != $defaultValue", field.safeName) + addEncode() endControlFlow("if") + } else { + // Message is fundamentally broken right now when it comes to evaluating "isDefault" + // We would need to check _every_ value and/or keep track of mutations + addEncode() } } - .build(), - ) - addFunction( - FunctionSpec.builder("encode") - .addParameter("to", "encoder", encoder) - .addModifiers(PUBLIC) - .throws(true) - .addStatement("var $container = encoder.container(keyedBy: %T.self)", codingKeys) - .apply { - if (type.declaredFieldsAndOneOfFields.any { it.codableName != null }) { - addStatement("let preferCamelCase = encoder.protoKeyNameEncodingStrategy == .camelCase") - } - if (type.declaredFields.any { !it.isOptional && (it.isCollection || it.isEnum || it.codableDefaultValue != null) }) { - addStatement("let includeDefaults = encoder.protoDefaultValuesEncodingStrategy == .include") - } - addStatement("") - - type.declaredFields.forEach { field -> - fun addEncode() { - var encode = "encode" - if (field.isRepeated) { - encode += "ProtoArray" - } else if (field.isMap) { - encode += "ProtoMap" - } else if (field.isOptional) { - encode += "IfPresent" - } - - val typeArg = if (field.typeName.isStringEncoded) { - "stringEncoded: " - } else { - "" - } - val (keys, args) = field.codableName?.let { codableName -> - Pair( - "preferCamelCase ? %3S : %2S", - arrayOf(field.name, codableName), - ) - } ?: Pair("%2S", arrayOf(field.name)) - - addStatement( - "try $container.$encode(${typeArg}self.%1N, forKey: $keys)", - field.safeName, - *args, + type.oneOfs.forEach { oneOf -> + beginControlFlow("switch", "self.%N", oneOf.name) + oneOf.fields.forEach { field -> + val (keys, args) = field.codableName?.let { codableName -> + Pair( + "preferCamelCase ? %3S : %2S", + arrayOf(field.name, codableName), ) - } + } ?: Pair("%2S", arrayOf(field.name)) - val defaultValue = field.codableDefaultValue - - if (field.isOptional) { - // A proto3 field that is defined with the optional keyword supports field presence. - // Fields that have a value set and that support field presence always include the field value - // in the JSON-encoded output, even if it is the default value. - addEncode() - } else if (field.isCollection) { - beginControlFlow("if", "includeDefaults || !self.%N.isEmpty", field.safeName) - addEncode() - endControlFlow("if") - } else if (field.isEnum) { - beginControlFlow("if", "includeDefaults || self.%N.rawValue != 0", field.safeName) - addEncode() - endControlFlow("if") - } else if (defaultValue != null) { - beginControlFlow("if", "includeDefaults || self.%N != $defaultValue", field.safeName) - addEncode() - endControlFlow("if") - } else { - // Message is fundamentally broken right now when it comes to evaluating "isDefault" - // We would need to check _every_ value and/or keep track of mutations - addEncode() - } - } - - type.oneOfs.forEach { oneOf -> - beginControlFlow("switch", "self.%N", oneOf.name) - oneOf.fields.forEach { field -> - val (keys, args) = field.codableName?.let { codableName -> - Pair( - "preferCamelCase ? %3S : %2S", - arrayOf(field.name, codableName), - ) - } ?: Pair("%2S", arrayOf(field.name)) - - addStatement( - "case .%1N(let %1N): try $container.encode(%1N, forKey: $keys)", - field.safeName, - *args, - ) - } - addStatement("case %T.none: break", OPTIONAL) - endControlFlow("switch") + addStatement( + "case .%1N(let %1N): try $container.encode(%1N, forKey: $keys)", + field.safeName, + *args, + ) } + addStatement("case %T.none: break", OPTIONAL) + endControlFlow("switch") } - .build(), - ) - } + } + .build(), + ) } - .build() - } + } + .build() private fun ParameterSpec.Builder.withFieldDefault(field: Field) = apply { when { @@ -1150,7 +1156,11 @@ class SwiftGenerator private constructor( .apply { type.declaredFields.filter { it.isRequiredParameter }.forEach { field -> val hasPropertyWrapper = !isIndirect(type, field) && (field.defaultedValue != null || field.isProtoDefaulted) - val fieldName = if (hasPropertyWrapper) { "_${field.safeName}" } else { field.safeName } + val fieldName = if (hasPropertyWrapper) { + "_${field.safeName}" + } else { + field.safeName + } addStatement( if (hasPropertyWrapper) { "self.%1N.wrappedValue = %2N" @@ -1763,23 +1773,21 @@ class SwiftGenerator private constructor( private fun generateEnclosing( type: EnclosingType, fileMembers: MutableList, - ): TypeSpec { - return TypeSpec.enumBuilder(type.typeName) - .addModifiers(PUBLIC) - .addDoc( - "%N\n", - "*Note:* This type only exists to maintain class structure for its nested types and " + - "is not an actual message.", - ) - .apply { - type.nestedTypes.forEach { nestedType -> - generateType(nestedType, fileMembers).forEach { - addType(it) - } + ): TypeSpec = TypeSpec.enumBuilder(type.typeName) + .addModifiers(PUBLIC) + .addDoc( + "%N\n", + "*Note:* This type only exists to maintain class structure for its nested types and " + + "is not an actual message.", + ) + .apply { + type.nestedTypes.forEach { nestedType -> + generateType(nestedType, fileMembers).forEach { + addType(it) } } - .build() - } + } + .build() companion object { // Always fully-qualified in case a message type is named `Data`. diff --git a/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHelpers.kt b/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHelpers.kt index be40e5758b..ee15e508e3 100644 --- a/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHelpers.kt +++ b/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/schema/SchemaHelpers.kt @@ -19,6 +19,4 @@ import com.squareup.wire.ProtoAdapter fun Schema.protoAdapter( messageTypeName: String, -): ProtoAdapter { - return protoAdapter(messageTypeName, includeUnknown = true) -} +): ProtoAdapter = protoAdapter(messageTypeName, includeUnknown = true) diff --git a/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/testing/files.kt b/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/testing/files.kt index 3d41b68a5c..6715260941 100644 --- a/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/testing/files.kt +++ b/wire-test-utils/src/commonMain/kotlin/com/squareup/wire/testing/files.kt @@ -28,9 +28,7 @@ private val otherSlash = if (slash == "/") "\\" else "/" * This returns a string where all other slashes are replaced with the slash of the local platform. * On Windows, `/` will be replaced with `\`. On other platforms, `\` will be replaced with `/`. */ -fun String.withPlatformSlashes(): String { - return replace(otherSlash, slash) -} +fun String.withPlatformSlashes(): String = replace(otherSlash, slash) fun FileSystem.readUtf8(pathString: String): String { read(pathString.toPath()) { @@ -38,12 +36,10 @@ fun FileSystem.readUtf8(pathString: String): String { } } -fun FileSystem.findFiles(path: String): Set { - return listRecursively(path.withPlatformSlashes().toPath()) - .filter { !metadata(it).isDirectory } - .map { it.toString() } - .toSet() -} +fun FileSystem.findFiles(path: String): Set = listRecursively(path.withPlatformSlashes().toPath()) + .filter { !metadata(it).isDirectory } + .map { it.toString() } + .toSet() /** * This asserts that [this] contains exactly in any order all [values] regardless of the slash they diff --git a/wire-test-utils/src/jvmMain/kotlin/com/squareup/wire/testing/UnwantedValueStripper.kt b/wire-test-utils/src/jvmMain/kotlin/com/squareup/wire/testing/UnwantedValueStripper.kt index 5e4c270f1a..44c91cc095 100644 --- a/wire-test-utils/src/jvmMain/kotlin/com/squareup/wire/testing/UnwantedValueStripper.kt +++ b/wire-test-utils/src/jvmMain/kotlin/com/squareup/wire/testing/UnwantedValueStripper.kt @@ -50,14 +50,12 @@ class UnwantedValueStripper( .build() } - fun stripOptionsAndDefaults(fieldDescriptorProto: FieldDescriptorProto): FieldDescriptorProto { - return fieldDescriptorProto.toBuilder() - .clearDefaultValue() - .apply { - if (clearJsonName) { - clearJsonName() - } + fun stripOptionsAndDefaults(fieldDescriptorProto: FieldDescriptorProto): FieldDescriptorProto = fieldDescriptorProto.toBuilder() + .clearDefaultValue() + .apply { + if (clearJsonName) { + clearJsonName() } - .build() - } + } + .build() } diff --git a/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/OneOfTest.kt b/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/OneOfTest.kt index 8a3d0b69a7..81b1ab9ae9 100644 --- a/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/OneOfTest.kt +++ b/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/OneOfTest.kt @@ -25,12 +25,15 @@ import org.junit.Assert.fail import org.junit.Test class OneOfTest { + @Suppress("ktlint:standard:property-naming") private val INITIAL_BYTES = byteArrayOf() // (Tag #1 << 3 | VARINT) = 8. + @Suppress("ktlint:standard:property-naming") private val FOO_BYTES = byteArrayOf(8, 17) // (Tag #3 << 3 | LENGTH_DELIMITED) = 26, string length = 6. + @Suppress("ktlint:standard:property-naming") private val BAR_BYTES = byteArrayOf( 26, 6, diff --git a/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/TestAllTypes.kt b/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/TestAllTypes.kt index 81165eab5b..4c1152bb99 100644 --- a/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/TestAllTypes.kt +++ b/wire-tests/jvm-kotlin-interop/src/test/kotlin/com/squareup/wire/TestAllTypes.kt @@ -107,9 +107,7 @@ class TestAllTypes { .ext_pack_bool(list(true, numRepeated)) } - private fun createAllTypes(numRepeated: Int = 2): AllTypes { - return getBuilder(numRepeated).build() - } + private fun createAllTypes(numRepeated: Int = 2): AllTypes = getBuilder(numRepeated).build() private val allTypes: AllTypes = createAllTypes() private val adapter = AllTypes.ADAPTER diff --git a/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt b/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt index b3239b1e77..044eba290c 100644 --- a/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt +++ b/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/TestAllTypesData.kt @@ -110,8 +110,10 @@ object TestAllTypesData { ) } + @Suppress("ktlint:standard:property-naming") val allTypes = message() + @Suppress("ktlint:standard:property-naming") const val expectedToString = ( "" + "AllTypes{opt_int32=111, opt_uint32=112, opt_sint32=113, opt_fixed32=114, opt_sfixed32=115," + @@ -136,6 +138,8 @@ object TestAllTypesData { "0, 122.0], array_double=[123.0, 123.0], ext_opt_bool=true, ext_rep_bool=[true, true], ext_" + "pack_bool=[true, true]}" ) + + @Suppress("ktlint:standard:property-naming") val expectedOutput = ( "" + // optional diff --git a/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/UnknownFieldsTest.kt b/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/UnknownFieldsTest.kt index 98d9294dec..926853dcd5 100644 --- a/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/UnknownFieldsTest.kt +++ b/wire-tests/multiplatform/src/commonTest/kotlin/com/squareup/wire/UnknownFieldsTest.kt @@ -33,6 +33,7 @@ class UnknownFieldsTest { private val v2Adapter = VersionTwo.ADAPTER @Test + @Suppress("ktlint:standard:property-naming") fun testUnknownFields() { val v1_obj = NestedVersionOne(i = 111) val v2_obj = NestedVersionTwo(