ProtobufCodeGenParser.swift 6.8 KB

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