ProtobufCodeGenParser.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. internal import Foundation
  17. internal import SwiftProtobuf
  18. internal import SwiftProtobufPluginLibrary
  19. internal import struct GRPCCodeGen.CodeGenerationRequest
  20. internal import struct GRPCCodeGen.SourceGenerator
  21. /// Parses a ``FileDescriptor`` object into a ``CodeGenerationRequest`` object.
  22. internal struct ProtobufCodeGenParser {
  23. let input: FileDescriptor
  24. let namer: SwiftProtobufNamer
  25. let extraModuleImports: [String]
  26. let protoToModuleMappings: ProtoFileToModuleMappings
  27. let accessLevel: SourceGenerator.Configuration.AccessLevel
  28. internal init(
  29. input: FileDescriptor,
  30. protoFileModuleMappings: ProtoFileToModuleMappings,
  31. extraModuleImports: [String],
  32. accessLevel: SourceGenerator.Configuration.AccessLevel
  33. ) {
  34. self.input = input
  35. self.extraModuleImports = extraModuleImports
  36. self.protoToModuleMappings = protoFileModuleMappings
  37. self.namer = SwiftProtobufNamer(
  38. currentFile: input,
  39. protoFileToModuleMappings: protoFileModuleMappings
  40. )
  41. self.accessLevel = accessLevel
  42. }
  43. internal func parse() throws -> CodeGenerationRequest {
  44. var header = self.input.header
  45. // Ensuring there is a blank line after the header.
  46. if !header.isEmpty && !header.hasSuffix("\n\n") {
  47. header.append("\n")
  48. }
  49. let leadingTrivia = """
  50. // DO NOT EDIT.
  51. // swift-format-ignore-file
  52. //
  53. // Generated by the gRPC Swift generator plugin for the protocol buffer compiler.
  54. // Source: \(self.input.name)
  55. //
  56. // For information on using the generated types, please see the documentation:
  57. // https://github.com/grpc/grpc-swift
  58. """
  59. let lookupSerializer: (String) -> String = { messageType in
  60. "GRPCProtobuf.ProtobufSerializer<\(messageType)>()"
  61. }
  62. let lookupDeserializer: (String) -> String = { messageType in
  63. "GRPCProtobuf.ProtobufDeserializer<\(messageType)>()"
  64. }
  65. let services = self.input.services.map {
  66. CodeGenerationRequest.ServiceDescriptor(
  67. descriptor: $0,
  68. package: input.package,
  69. protobufNamer: self.namer,
  70. file: self.input
  71. )
  72. }
  73. return CodeGenerationRequest(
  74. fileName: self.input.name,
  75. leadingTrivia: header + leadingTrivia,
  76. dependencies: self.codeDependencies,
  77. services: services,
  78. lookupSerializer: lookupSerializer,
  79. lookupDeserializer: lookupDeserializer
  80. )
  81. }
  82. }
  83. extension ProtobufCodeGenParser {
  84. fileprivate var codeDependencies: [CodeGenerationRequest.Dependency] {
  85. var codeDependencies: [CodeGenerationRequest.Dependency] = [
  86. .init(module: "GRPCProtobuf", accessLevel: .internal)
  87. ]
  88. // Adding as dependencies the modules containing generated code or types for
  89. // '.proto' files imported in the '.proto' file we are parsing.
  90. codeDependencies.append(
  91. contentsOf: (self.protoToModuleMappings.neededModules(forFile: self.input) ?? []).map {
  92. CodeGenerationRequest.Dependency(module: $0, accessLevel: self.accessLevel)
  93. }
  94. )
  95. // Adding extra imports passed in as an option to the plugin.
  96. codeDependencies.append(
  97. contentsOf: self.extraModuleImports.sorted().map {
  98. CodeGenerationRequest.Dependency(module: $0, accessLevel: self.accessLevel)
  99. }
  100. )
  101. return codeDependencies
  102. }
  103. }
  104. extension CodeGenerationRequest.ServiceDescriptor {
  105. fileprivate init(
  106. descriptor: ServiceDescriptor,
  107. package: String,
  108. protobufNamer: SwiftProtobufNamer,
  109. file: FileDescriptor
  110. ) {
  111. let methods = descriptor.methods.map {
  112. CodeGenerationRequest.ServiceDescriptor.MethodDescriptor(
  113. descriptor: $0,
  114. protobufNamer: protobufNamer
  115. )
  116. }
  117. let name = CodeGenerationRequest.Name(
  118. base: descriptor.name,
  119. generatedUpperCase: NamingUtils.toUpperCamelCase(descriptor.name),
  120. generatedLowerCase: NamingUtils.toLowerCamelCase(descriptor.name)
  121. )
  122. // Packages that are based on the path of the '.proto' file usually
  123. // contain dots. For example: "grpc.test".
  124. let namespace = CodeGenerationRequest.Name(
  125. base: package,
  126. generatedUpperCase: protobufNamer.formattedUpperCasePackage(file: file),
  127. generatedLowerCase: protobufNamer.formattedLowerCasePackage(file: file)
  128. )
  129. let documentation = descriptor.protoSourceComments()
  130. self.init(documentation: documentation, name: name, namespace: namespace, methods: methods)
  131. }
  132. }
  133. extension CodeGenerationRequest.ServiceDescriptor.MethodDescriptor {
  134. fileprivate init(descriptor: MethodDescriptor, protobufNamer: SwiftProtobufNamer) {
  135. let name = CodeGenerationRequest.Name(
  136. base: descriptor.name,
  137. generatedUpperCase: NamingUtils.toUpperCamelCase(descriptor.name),
  138. generatedLowerCase: NamingUtils.toLowerCamelCase(descriptor.name)
  139. )
  140. let documentation = descriptor.protoSourceComments()
  141. self.init(
  142. documentation: documentation,
  143. name: name,
  144. isInputStreaming: descriptor.clientStreaming,
  145. isOutputStreaming: descriptor.serverStreaming,
  146. inputType: protobufNamer.fullName(message: descriptor.inputType),
  147. outputType: protobufNamer.fullName(message: descriptor.outputType)
  148. )
  149. }
  150. }
  151. extension FileDescriptor {
  152. fileprivate var header: String {
  153. var header = String()
  154. // Field number used to collect the syntax field which is usually the first
  155. // declaration in a.proto file.
  156. // See more here:
  157. // https://github.com/apple/swift-protobuf/blob/main/Protos/SwiftProtobuf/google/protobuf/descriptor.proto
  158. let syntaxPath = IndexPath(index: 12)
  159. if let syntaxLocation = self.sourceCodeInfoLocation(path: syntaxPath) {
  160. header = syntaxLocation.asSourceComment(
  161. commentPrefix: "///",
  162. leadingDetachedPrefix: "//"
  163. )
  164. }
  165. return header
  166. }
  167. }
  168. extension SwiftProtobufNamer {
  169. internal func formattedUpperCasePackage(file: FileDescriptor) -> String {
  170. let unformattedPackage = self.typePrefix(forFile: file)
  171. return unformattedPackage.trimTrailingUnderscores()
  172. }
  173. internal func formattedLowerCasePackage(file: FileDescriptor) -> String {
  174. let upperCasePackage = self.formattedUpperCasePackage(file: file)
  175. let lowerCaseComponents = upperCasePackage.split(separator: "_").map { component in
  176. NamingUtils.toLowerCamelCase(String(component))
  177. }
  178. return lowerCaseComponents.joined(separator: "_")
  179. }
  180. }
  181. extension String {
  182. internal func trimTrailingUnderscores() -> String {
  183. if let index = self.lastIndex(where: { $0 != "_" }) {
  184. return String(self[...index])
  185. } else {
  186. return ""
  187. }
  188. }
  189. }