|
| 1 | +/* |
| 2 | + * Copyright 2023-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.rpc.protobuf |
| 6 | + |
| 7 | +import com.google.protobuf.DescriptorProtos |
| 8 | +import com.google.protobuf.Descriptors |
| 9 | +import com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest |
| 10 | +import kotlinx.rpc.protobuf.model.* |
| 11 | + |
| 12 | +private val modelCache = mutableMapOf<Descriptors.GenericDescriptor, Any>() |
| 13 | + |
| 14 | +fun CodeGeneratorRequest.toCommonModel(): Model { |
| 15 | + val protoFileMap = protoFileList.associateBy { it.name } |
| 16 | + val fileDescriptors = mutableMapOf<String, Descriptors.FileDescriptor>() |
| 17 | + |
| 18 | + val files = protoFileList.map { protoFile -> protoFile.toDescriptor(protoFileMap, fileDescriptors) } |
| 19 | + |
| 20 | + return Model( |
| 21 | + files = files.map { it.toCommonModel() } |
| 22 | + ) |
| 23 | +} |
| 24 | + |
| 25 | +private inline fun <D, reified T> D.cached(block: (D) -> T): T |
| 26 | + where D : Descriptors.GenericDescriptor, T : Any { |
| 27 | + if (modelCache.containsKey(this)) { |
| 28 | + return modelCache[this] as T |
| 29 | + } |
| 30 | + val declaration = block(this) |
| 31 | + modelCache[this] = declaration |
| 32 | + return declaration |
| 33 | +} |
| 34 | + |
| 35 | +private fun Descriptors.FileDescriptor.toCommonModel(): FileDeclaration = cached { |
| 36 | + return FileDeclaration( |
| 37 | + name = kotlinFileName(), |
| 38 | + packageName = FqName.Package.fromString(`package`), |
| 39 | + dependencies = dependencies.map { it.toCommonModel() }, |
| 40 | + messageDeclarations = messageTypes.map { it.toCommonModel() }, |
| 41 | + enumDeclarations = enumTypes.map { it.toCommonModel() }, |
| 42 | + serviceDeclarations = services.map { it.toCommonModel() }, |
| 43 | + deprecated = options.deprecated, |
| 44 | + doc = null, |
| 45 | + ) |
| 46 | +} |
| 47 | + |
| 48 | +private fun Descriptors.Descriptor.toCommonModel(): MessageDeclaration = cached { |
| 49 | + val regularFields = fields.filter { field -> field.realContainingOneof == null }.map { it.toCommonModel() } |
| 50 | + |
| 51 | + return MessageDeclaration( |
| 52 | + outerClassName = fqName(), |
| 53 | + name = fqName(), |
| 54 | + actualFields = regularFields, |
| 55 | + // get all oneof declarations that are not created from an optional in proto3 https://github.com/googleapis/api-linter/issues/1323 |
| 56 | + oneOfDeclarations = oneofs.filter { it.fields[0].realContainingOneof != null }.map { it.toCommonModel() }, |
| 57 | + enumDeclarations = enumTypes.map { it.toCommonModel() }, |
| 58 | + nestedDeclarations = nestedTypes.map { it.toCommonModel() }, |
| 59 | + deprecated = options.deprecated, |
| 60 | + doc = null, |
| 61 | + ) |
| 62 | +} |
| 63 | + |
| 64 | +private fun Descriptors.FieldDescriptor.toCommonModel(): FieldDeclaration = cached { |
| 65 | + toProto().hasProto3Optional() |
| 66 | + return FieldDeclaration( |
| 67 | + name = fqName().simpleName, |
| 68 | + number = number, |
| 69 | + type = modelType(), |
| 70 | + nullable = isNullable(), |
| 71 | + deprecated = options.deprecated, |
| 72 | + doc = null, |
| 73 | + proto = toProto(), |
| 74 | + ) |
| 75 | +} |
| 76 | + |
| 77 | +private fun Descriptors.FieldDescriptor.isNullable(): Boolean { |
| 78 | + // aligns with edition settings and backward compatibility with proto2 and proto3 |
| 79 | + return hasPresence() && !isRequired && !hasDefaultValue() |
| 80 | +} |
| 81 | + |
| 82 | +private fun Descriptors.OneofDescriptor.toCommonModel(): OneOfDeclaration = cached { |
| 83 | + return OneOfDeclaration( |
| 84 | + name = fqName(), |
| 85 | + variants = fields.map { it.toCommonModel() }, |
| 86 | + descriptor = this |
| 87 | + ) |
| 88 | +} |
| 89 | + |
| 90 | +private fun Descriptors.EnumDescriptor.toCommonModel(): EnumDeclaration = cached { |
| 91 | + val entriesMap = mutableMapOf<Int, EnumDeclaration.Entry>() |
| 92 | + val aliases = mutableListOf<EnumDeclaration.Alias>() |
| 93 | + |
| 94 | + values.forEach { value -> |
| 95 | + if (entriesMap.containsKey(value.number)) { |
| 96 | + val original = entriesMap.getValue(value.number) |
| 97 | + aliases.add(value.toAliasModel(original)) |
| 98 | + } else { |
| 99 | + entriesMap[value.number] = value.toCommonModel() |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + if (!options.allowAlias && aliases.isNotEmpty()) { |
| 104 | + error("Enum ${fullName} has aliases: ${aliases.joinToString { it.name.simpleName }}") |
| 105 | + } |
| 106 | + |
| 107 | + return EnumDeclaration( |
| 108 | + outerClassName = fqName(), |
| 109 | + name = fqName(), |
| 110 | + originalEntries = entriesMap.values.toList(), |
| 111 | + aliases = aliases, |
| 112 | + deprecated = options.deprecated, |
| 113 | + doc = null |
| 114 | + ) |
| 115 | +} |
| 116 | + |
| 117 | +private fun Descriptors.EnumValueDescriptor.toCommonModel(): EnumDeclaration.Entry = cached { |
| 118 | + return EnumDeclaration.Entry( |
| 119 | + name = fqName(), |
| 120 | + deprecated = options.deprecated, |
| 121 | + doc = null, |
| 122 | + ) |
| 123 | +} |
| 124 | + |
| 125 | +// no caching, as it would conflict with .toModel |
| 126 | +private fun Descriptors.EnumValueDescriptor.toAliasModel(original: EnumDeclaration.Entry): EnumDeclaration.Alias { |
| 127 | + return EnumDeclaration.Alias( |
| 128 | + name = fqName(), |
| 129 | + original = original, |
| 130 | + deprecated = options.deprecated, |
| 131 | + doc = null, |
| 132 | + ) |
| 133 | +} |
| 134 | + |
| 135 | +private fun Descriptors.ServiceDescriptor.toCommonModel(): ServiceDeclaration = cached { |
| 136 | + return ServiceDeclaration( |
| 137 | + name = fqName(), |
| 138 | + methods = methods.map { it.toCommonModel() } |
| 139 | + ) |
| 140 | +} |
| 141 | + |
| 142 | +private fun Descriptors.MethodDescriptor.toCommonModel(): MethodDeclaration = cached { |
| 143 | + return MethodDeclaration( |
| 144 | + name = name, |
| 145 | + clientStreaming = isClientStreaming, |
| 146 | + serverStreaming = isServerStreaming, |
| 147 | + inputType = lazy { inputType.toCommonModel() }, |
| 148 | + outputType = lazy { outputType.toCommonModel() } |
| 149 | + ) |
| 150 | +} |
| 151 | + |
| 152 | + |
| 153 | +private fun DescriptorProtos.FileDescriptorProto.toDescriptor( |
| 154 | + protoFileMap: Map<String, DescriptorProtos.FileDescriptorProto>, |
| 155 | + cache: MutableMap<String, Descriptors.FileDescriptor> |
| 156 | +): Descriptors.FileDescriptor { |
| 157 | + if (cache.containsKey(name)) return cache[name]!! |
| 158 | + |
| 159 | + val dependencies = dependencyList.map { depName -> |
| 160 | + val depProto = protoFileMap[depName] ?: error("Missing dependency: $depName") |
| 161 | + depProto.toDescriptor(protoFileMap, cache) |
| 162 | + }.toTypedArray() |
| 163 | + |
| 164 | + val fileDescriptor = Descriptors.FileDescriptor.buildFrom(this, dependencies) |
| 165 | + cache[name] = fileDescriptor |
| 166 | + return fileDescriptor |
| 167 | +} |
| 168 | + |
| 169 | +//// Type Conversion Extension //// |
| 170 | + |
| 171 | +private fun Descriptors.FieldDescriptor.modelType(): FieldType { |
| 172 | + val baseType = when (type) { |
| 173 | + Descriptors.FieldDescriptor.Type.DOUBLE -> FieldType.IntegralType.DOUBLE |
| 174 | + Descriptors.FieldDescriptor.Type.FLOAT -> FieldType.IntegralType.FLOAT |
| 175 | + Descriptors.FieldDescriptor.Type.INT64 -> FieldType.IntegralType.INT64 |
| 176 | + Descriptors.FieldDescriptor.Type.UINT64 -> FieldType.IntegralType.UINT64 |
| 177 | + Descriptors.FieldDescriptor.Type.INT32 -> FieldType.IntegralType.INT32 |
| 178 | + Descriptors.FieldDescriptor.Type.FIXED64 -> FieldType.IntegralType.FIXED64 |
| 179 | + Descriptors.FieldDescriptor.Type.FIXED32 -> FieldType.IntegralType.FIXED32 |
| 180 | + Descriptors.FieldDescriptor.Type.BOOL -> FieldType.IntegralType.BOOL |
| 181 | + Descriptors.FieldDescriptor.Type.STRING -> FieldType.IntegralType.STRING |
| 182 | + Descriptors.FieldDescriptor.Type.BYTES -> FieldType.IntegralType.BYTES |
| 183 | + Descriptors.FieldDescriptor.Type.UINT32 -> FieldType.IntegralType.UINT32 |
| 184 | + Descriptors.FieldDescriptor.Type.SFIXED32 -> FieldType.IntegralType.SFIXED32 |
| 185 | + Descriptors.FieldDescriptor.Type.SFIXED64 -> FieldType.IntegralType.SFIXED64 |
| 186 | + Descriptors.FieldDescriptor.Type.SINT32 -> FieldType.IntegralType.SINT32 |
| 187 | + Descriptors.FieldDescriptor.Type.SINT64 -> FieldType.IntegralType.SINT64 |
| 188 | + Descriptors.FieldDescriptor.Type.ENUM -> FieldType.Reference(lazy { enumType!!.toCommonModel().name }) |
| 189 | + Descriptors.FieldDescriptor.Type.MESSAGE -> FieldType.Reference(lazy { messageType!!.toCommonModel().name }) |
| 190 | + Descriptors.FieldDescriptor.Type.GROUP -> error("GROUP type is unsupported") |
| 191 | + } |
| 192 | + |
| 193 | + if (isRepeated) { |
| 194 | + return FieldType.List(baseType) |
| 195 | + } |
| 196 | + |
| 197 | + // TODO: Handle map type |
| 198 | + |
| 199 | + return baseType |
| 200 | +} |
| 201 | + |
| 202 | +//// Utility Extensions //// |
| 203 | + |
| 204 | +private fun Descriptors.FileDescriptor.kotlinFileName(): String { |
| 205 | + return "${protoFileNameToKotlinName()}.kt" |
| 206 | +} |
| 207 | + |
| 208 | +private fun Descriptors.FileDescriptor.protoFileNameToKotlinName(): String { |
| 209 | + return name.removeSuffix(".proto").fullProtoNameToKotlin(firstLetterUpper = true) |
| 210 | +} |
| 211 | + |
| 212 | + |
| 213 | +private fun String.fullProtoNameToKotlin(firstLetterUpper: Boolean = false): String { |
| 214 | + val lastDelimiterIndex = indexOfLast { it == '.' || it == '/' } |
| 215 | + return if (lastDelimiterIndex != -1) { |
| 216 | + val packageName = substring(0, lastDelimiterIndex) |
| 217 | + val name = substring(lastDelimiterIndex + 1) |
| 218 | + val delimiter = this[lastDelimiterIndex] |
| 219 | + return "$packageName$delimiter${name.simpleProtoNameToKotlin(firstLetterUpper = true)}" |
| 220 | + } else { |
| 221 | + simpleProtoNameToKotlin(firstLetterUpper) |
| 222 | + } |
| 223 | +} |
| 224 | + |
| 225 | + |
| 226 | +private val snakeRegExp = "(_[a-z]|-[a-z])".toRegex() |
| 227 | + |
| 228 | +private fun String.snakeToCamelCase(): String { |
| 229 | + return replace(snakeRegExp) { it.value.last().uppercase() } |
| 230 | +} |
| 231 | + |
| 232 | +private fun String.simpleProtoNameToKotlin(firstLetterUpper: Boolean = false): String { |
| 233 | + return snakeToCamelCase().run { |
| 234 | + if (firstLetterUpper) { |
| 235 | + replaceFirstChar { it.uppercase() } |
| 236 | + } else { |
| 237 | + this |
| 238 | + } |
| 239 | + } |
| 240 | +} |
| 241 | + |
0 commit comments