ClientCodeTranslator.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. /*
  2. * Copyright 2023, 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. /// Creates a representation for the client code that will be generated based on the ``CodeGenerationRequest`` object
  17. /// specifications, using types from ``StructuredSwiftRepresentation``.
  18. ///
  19. /// For example, in the case of a service called "Bar", in the "foo" namespace which has
  20. /// one method "baz", the ``ClientCodeTranslator`` will create
  21. /// a representation for the following generated code:
  22. ///
  23. /// ```swift
  24. /// public protocol Foo_BarClientProtocol: Sendable {
  25. /// func baz<R: Sendable>(
  26. /// request: ClientRequest.Single<foo.Bar.Methods.baz.Input>,
  27. /// serializer: some MessageSerializer<foo.Bar.Methods.baz.Input>,
  28. /// deserializer: some MessageDeserializer<foo.Bar.Methods.baz.Output>,
  29. /// _ body: @Sendable @escaping (ClientResponse.Single<foo.Bar.Methods.Baz.Output>) async throws -> R
  30. /// ) async throws -> ServerResponse.Stream<foo.Bar.Methods.Baz.Output>
  31. /// }
  32. /// extension Foo.Bar.ClientProtocol {
  33. /// public func get<R: Sendable>(
  34. /// request: ClientRequest.Single<Foo.Bar.Methods.Baz.Input>,
  35. /// _ body: @Sendable @escaping (ClientResponse.Single<Foo.Bar.Methods.Baz.Output>) async throws -> R
  36. /// ) async rethrows -> R {
  37. /// try await self.baz(
  38. /// request: request,
  39. /// serializer: ProtobufSerializer<Foo.Bar.Methods.Baz.Input>(),
  40. /// deserializer: ProtobufDeserializer<Foo.Bar.Methods.Baz.Output>(),
  41. /// body
  42. /// )
  43. /// }
  44. /// public struct foo_BarClient: foo.Bar.ClientProtocol {
  45. /// private let client: GRPCCore.GRPCClient
  46. /// public init(client: GRPCCore.GRPCClient) {
  47. /// self.client = client
  48. /// }
  49. /// public func methodA<R: Sendable>(
  50. /// request: ClientRequest.Stream<namespaceA.ServiceA.Methods.methodA.Input>,
  51. /// serializer: some MessageSerializer<namespaceA.ServiceA.Methods.methodA.Input>,
  52. /// deserializer: some MessageDeserializer<namespaceA.ServiceA.Methods.methodA.Output>,
  53. /// _ body: @Sendable @escaping (ClientResponse.Single<namespaceA.ServiceA.Methods.methodA.Output>) async throws -> R
  54. /// ) async rethrows -> R {
  55. /// try await self.client.clientStreaming(
  56. /// request: request,
  57. /// descriptor: NamespaceA.ServiceA.Methods.MethodA.descriptor,
  58. /// serializer: serializer,
  59. /// deserializer: deserializer,
  60. /// handler: body
  61. /// )
  62. /// }
  63. /// }
  64. ///```
  65. struct ClientCodeTranslator: SpecializedTranslator {
  66. var accessLevel: SourceGenerator.Configuration.AccessLevel
  67. init(accessLevel: SourceGenerator.Configuration.AccessLevel) {
  68. self.accessLevel = accessLevel
  69. }
  70. func translate(from codeGenerationRequest: CodeGenerationRequest) throws -> [CodeBlock] {
  71. var codeBlocks = [CodeBlock]()
  72. for service in codeGenerationRequest.services {
  73. codeBlocks.append(
  74. .declaration(
  75. .commentable(
  76. .doc(service.documentation),
  77. self.makeClientProtocol(for: service, in: codeGenerationRequest)
  78. )
  79. )
  80. )
  81. codeBlocks.append(
  82. .declaration(self.makeExtensionProtocol(for: service, in: codeGenerationRequest))
  83. )
  84. codeBlocks.append(
  85. .declaration(
  86. .commentable(
  87. .doc(service.documentation),
  88. self.makeClientStruct(for: service, in: codeGenerationRequest)
  89. )
  90. )
  91. )
  92. }
  93. return codeBlocks
  94. }
  95. }
  96. extension ClientCodeTranslator {
  97. private func makeClientProtocol(
  98. for service: CodeGenerationRequest.ServiceDescriptor,
  99. in codeGenerationRequest: CodeGenerationRequest
  100. ) -> Declaration {
  101. let methods = service.methods.map {
  102. self.makeClientProtocolMethod(
  103. for: $0,
  104. in: service,
  105. from: codeGenerationRequest,
  106. generateSerializerDeserializer: false
  107. )
  108. }
  109. let clientProtocol = Declaration.protocol(
  110. ProtocolDescription(
  111. accessModifier: self.accessModifier,
  112. name: "\(service.namespacedGeneratedName)ClientProtocol",
  113. conformances: ["Sendable"],
  114. members: methods
  115. )
  116. )
  117. return clientProtocol
  118. }
  119. private func makeExtensionProtocol(
  120. for service: CodeGenerationRequest.ServiceDescriptor,
  121. in codeGenerationRequest: CodeGenerationRequest
  122. ) -> Declaration {
  123. let methods = service.methods.map {
  124. self.makeClientProtocolMethod(
  125. for: $0,
  126. in: service,
  127. from: codeGenerationRequest,
  128. generateSerializerDeserializer: true,
  129. accessModifier: self.accessModifier
  130. )
  131. }
  132. let clientProtocolExtension = Declaration.extension(
  133. ExtensionDescription(
  134. onType: "\(service.namespacedTypealiasGeneratedName).ClientProtocol",
  135. declarations: methods
  136. )
  137. )
  138. return clientProtocolExtension
  139. }
  140. private func makeClientProtocolMethod(
  141. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  142. in service: CodeGenerationRequest.ServiceDescriptor,
  143. from codeGenerationRequest: CodeGenerationRequest,
  144. generateSerializerDeserializer: Bool,
  145. accessModifier: AccessModifier? = nil
  146. ) -> Declaration {
  147. let methodParameters = self.makeParameters(
  148. for: method,
  149. in: service,
  150. from: codeGenerationRequest,
  151. generateSerializerDeserializer: generateSerializerDeserializer
  152. )
  153. let functionSignature = FunctionSignatureDescription(
  154. accessModifier: accessModifier,
  155. kind: .function(
  156. name: method.name.generatedLowerCase,
  157. isStatic: false
  158. ),
  159. generics: [.member("R")],
  160. parameters: methodParameters,
  161. keywords: [.async, .throws],
  162. returnType: .identifierType(.member("R")),
  163. whereClause: WhereClause(requirements: [.conformance("R", "Sendable")])
  164. )
  165. if generateSerializerDeserializer {
  166. let body = self.makeSerializerDeserializerCall(
  167. for: method,
  168. in: service,
  169. from: codeGenerationRequest
  170. )
  171. return .function(signature: functionSignature, body: body)
  172. } else {
  173. return .commentable(.doc(method.documentation), .function(signature: functionSignature))
  174. }
  175. }
  176. private func makeSerializerDeserializerCall(
  177. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  178. in service: CodeGenerationRequest.ServiceDescriptor,
  179. from codeGenerationRequest: CodeGenerationRequest
  180. ) -> [CodeBlock] {
  181. let functionCall = Expression.functionCall(
  182. calledExpression: .memberAccess(
  183. MemberAccessDescription(
  184. left: .identifierPattern("self"),
  185. right: method.name.generatedLowerCase
  186. )
  187. ),
  188. arguments: [
  189. FunctionArgumentDescription(label: "request", expression: .identifierPattern("request")),
  190. FunctionArgumentDescription(
  191. label: "serializer",
  192. expression: .identifierPattern(
  193. codeGenerationRequest.lookupSerializer(
  194. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  195. )
  196. )
  197. ),
  198. FunctionArgumentDescription(
  199. label: "deserializer",
  200. expression: .identifierPattern(
  201. codeGenerationRequest.lookupDeserializer(
  202. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  203. )
  204. )
  205. ),
  206. FunctionArgumentDescription(expression: .identifierPattern("body")),
  207. ]
  208. )
  209. let awaitFunctionCall = Expression.unaryKeyword(kind: .await, expression: functionCall)
  210. let tryAwaitFunctionCall = Expression.unaryKeyword(kind: .try, expression: awaitFunctionCall)
  211. return [CodeBlock(item: .expression(tryAwaitFunctionCall))]
  212. }
  213. private func makeParameters(
  214. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  215. in service: CodeGenerationRequest.ServiceDescriptor,
  216. from codeGenerationRequest: CodeGenerationRequest,
  217. generateSerializerDeserializer: Bool
  218. ) -> [ParameterDescription] {
  219. var parameters = [ParameterDescription]()
  220. parameters.append(self.clientRequestParameter(for: method, in: service))
  221. if !generateSerializerDeserializer {
  222. parameters.append(self.serializerParameter(for: method, in: service))
  223. parameters.append(self.deserializerParameter(for: method, in: service))
  224. }
  225. parameters.append(self.bodyParameter(for: method, in: service))
  226. return parameters
  227. }
  228. private func clientRequestParameter(
  229. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  230. in service: CodeGenerationRequest.ServiceDescriptor
  231. ) -> ParameterDescription {
  232. let requestType = method.isInputStreaming ? "Stream" : "Single"
  233. let clientRequestType = ExistingTypeDescription.member(["ClientRequest", requestType])
  234. return ParameterDescription(
  235. label: "request",
  236. type: .generic(
  237. wrapper: clientRequestType,
  238. wrapped: .member(
  239. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  240. )
  241. )
  242. )
  243. }
  244. private func serializerParameter(
  245. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  246. in service: CodeGenerationRequest.ServiceDescriptor
  247. ) -> ParameterDescription {
  248. return ParameterDescription(
  249. label: "serializer",
  250. type: ExistingTypeDescription.some(
  251. .generic(
  252. wrapper: .member("MessageSerializer"),
  253. wrapped: .member(
  254. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  255. )
  256. )
  257. )
  258. )
  259. }
  260. private func deserializerParameter(
  261. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  262. in service: CodeGenerationRequest.ServiceDescriptor
  263. ) -> ParameterDescription {
  264. return ParameterDescription(
  265. label: "deserializer",
  266. type: ExistingTypeDescription.some(
  267. .generic(
  268. wrapper: .member("MessageDeserializer"),
  269. wrapped: .member(
  270. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  271. )
  272. )
  273. )
  274. )
  275. }
  276. private func bodyParameter(
  277. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  278. in service: CodeGenerationRequest.ServiceDescriptor
  279. ) -> ParameterDescription {
  280. let clientStreaming = method.isOutputStreaming ? "Stream" : "Single"
  281. let closureParameterType = ExistingTypeDescription.generic(
  282. wrapper: .member(["ClientResponse", clientStreaming]),
  283. wrapped: .member(
  284. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  285. )
  286. )
  287. let bodyClosure = ClosureSignatureDescription(
  288. parameters: [.init(type: closureParameterType)],
  289. keywords: [.async, .throws],
  290. returnType: .identifierType(.member("R")),
  291. sendable: true,
  292. escaping: true
  293. )
  294. return ParameterDescription(name: "body", type: .closure(bodyClosure))
  295. }
  296. private func makeClientStruct(
  297. for service: CodeGenerationRequest.ServiceDescriptor,
  298. in codeGenerationRequest: CodeGenerationRequest
  299. ) -> Declaration {
  300. let clientProperty = Declaration.variable(
  301. accessModifier: .private,
  302. kind: .let,
  303. left: "client",
  304. type: .member(["GRPCCore", "GRPCClient"])
  305. )
  306. let initializer = self.makeClientVariable()
  307. let methods = service.methods.map {
  308. Declaration.commentable(
  309. .doc($0.documentation),
  310. self.makeClientMethod(for: $0, in: service, from: codeGenerationRequest)
  311. )
  312. }
  313. return .struct(
  314. StructDescription(
  315. accessModifier: self.accessModifier,
  316. name: "\(service.namespacedGeneratedName)Client",
  317. conformances: ["\(service.namespacedTypealiasGeneratedName).ClientProtocol"],
  318. members: [clientProperty, initializer] + methods
  319. )
  320. )
  321. }
  322. private func makeClientVariable() -> Declaration {
  323. let initializerBody = Expression.assignment(
  324. left: .memberAccess(
  325. MemberAccessDescription(left: .identifierPattern("self"), right: "client")
  326. ),
  327. right: .identifierPattern("client")
  328. )
  329. return .function(
  330. signature: .init(
  331. accessModifier: self.accessModifier,
  332. kind: .initializer,
  333. parameters: [.init(label: "client", type: .member(["GRPCCore", "GRPCClient"]))]
  334. ),
  335. body: [CodeBlock(item: .expression(initializerBody))]
  336. )
  337. }
  338. private func clientMethod(
  339. isInputStreaming: Bool,
  340. isOutputStreaming: Bool
  341. ) -> String {
  342. switch (isInputStreaming, isOutputStreaming) {
  343. case (true, true):
  344. return "bidirectionalStreaming"
  345. case (true, false):
  346. return "clientStreaming"
  347. case (false, true):
  348. return "serverStreaming"
  349. case (false, false):
  350. return "unary"
  351. }
  352. }
  353. private func makeClientMethod(
  354. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  355. in service: CodeGenerationRequest.ServiceDescriptor,
  356. from codeGenerationRequest: CodeGenerationRequest
  357. ) -> Declaration {
  358. let parameters = self.makeParameters(
  359. for: method,
  360. in: service,
  361. from: codeGenerationRequest,
  362. generateSerializerDeserializer: false
  363. )
  364. let grpcMethodName = self.clientMethod(
  365. isInputStreaming: method.isInputStreaming,
  366. isOutputStreaming: method.isOutputStreaming
  367. )
  368. let functionCall = Expression.functionCall(
  369. calledExpression: .memberAccess(
  370. MemberAccessDescription(left: .identifierPattern("self.client"), right: "\(grpcMethodName)")
  371. ),
  372. arguments: [
  373. .init(label: "request", expression: .identifierPattern("request")),
  374. .init(
  375. label: "descriptor",
  376. expression: .identifierPattern(
  377. "\(service.namespacedTypealiasGeneratedName).Methods.\(method.name.generatedUpperCase).descriptor"
  378. )
  379. ),
  380. .init(label: "serializer", expression: .identifierPattern("serializer")),
  381. .init(label: "deserializer", expression: .identifierPattern("deserializer")),
  382. .init(label: "handler", expression: .identifierPattern("body")),
  383. ]
  384. )
  385. let body = UnaryKeywordDescription(
  386. kind: .try,
  387. expression: .unaryKeyword(kind: .await, expression: functionCall)
  388. )
  389. return .function(
  390. accessModifier: self.accessModifier,
  391. kind: .function(
  392. name: "\(method.name.generatedLowerCase)",
  393. isStatic: false
  394. ),
  395. generics: [.member("R")],
  396. parameters: parameters,
  397. keywords: [.async, .throws],
  398. returnType: .identifierType(.member("R")),
  399. whereClause: WhereClause(requirements: [.conformance("R", "Sendable")]),
  400. body: [.expression(.unaryKeyword(body))]
  401. )
  402. }
  403. fileprivate enum InputOutputType {
  404. case input
  405. case output
  406. }
  407. /// Generates the fully qualified name of the typealias for the input or output type of a method.
  408. private func methodInputOutputTypealias(
  409. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  410. service: CodeGenerationRequest.ServiceDescriptor,
  411. type: InputOutputType
  412. ) -> String {
  413. var components: String =
  414. "\(service.namespacedTypealiasGeneratedName).Methods.\(method.name.generatedUpperCase)"
  415. switch type {
  416. case .input:
  417. components.append(".Input")
  418. case .output:
  419. components.append(".Output")
  420. }
  421. return components
  422. }
  423. }