ClientCodeTranslator.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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.bazOutput>
  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.namespacedPrefix)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.namespacedTypealiasPrefix).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,
  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(left: .identifierPattern("self"), right: method.name)
  184. ),
  185. arguments: [
  186. FunctionArgumentDescription(label: "request", expression: .identifierPattern("request")),
  187. FunctionArgumentDescription(
  188. label: "serializer",
  189. expression: .identifierPattern(
  190. codeGenerationRequest.lookupSerializer(
  191. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  192. )
  193. )
  194. ),
  195. FunctionArgumentDescription(
  196. label: "deserializer",
  197. expression: .identifierPattern(
  198. codeGenerationRequest.lookupDeserializer(
  199. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  200. )
  201. )
  202. ),
  203. FunctionArgumentDescription(expression: .identifierPattern("body")),
  204. ]
  205. )
  206. let awaitFunctionCall = Expression.unaryKeyword(kind: .await, expression: functionCall)
  207. let tryAwaitFunctionCall = Expression.unaryKeyword(kind: .try, expression: awaitFunctionCall)
  208. return [CodeBlock(item: .expression(tryAwaitFunctionCall))]
  209. }
  210. private func makeParameters(
  211. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  212. in service: CodeGenerationRequest.ServiceDescriptor,
  213. from codeGenerationRequest: CodeGenerationRequest,
  214. generateSerializerDeserializer: Bool
  215. ) -> [ParameterDescription] {
  216. var parameters = [ParameterDescription]()
  217. parameters.append(self.clientRequestParameter(for: method, in: service))
  218. if !generateSerializerDeserializer {
  219. parameters.append(self.serializerParameter(for: method, in: service))
  220. parameters.append(self.deserializerParameter(for: method, in: service))
  221. }
  222. parameters.append(self.bodyParameter(for: method, in: service))
  223. return parameters
  224. }
  225. private func clientRequestParameter(
  226. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  227. in service: CodeGenerationRequest.ServiceDescriptor
  228. ) -> ParameterDescription {
  229. let requestType = method.isInputStreaming ? "Stream" : "Single"
  230. let clientRequestType = ExistingTypeDescription.member(["ClientRequest", requestType])
  231. return ParameterDescription(
  232. label: "request",
  233. type: .generic(
  234. wrapper: clientRequestType,
  235. wrapped: .member(
  236. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  237. )
  238. )
  239. )
  240. }
  241. private func serializerParameter(
  242. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  243. in service: CodeGenerationRequest.ServiceDescriptor
  244. ) -> ParameterDescription {
  245. return ParameterDescription(
  246. label: "serializer",
  247. type: ExistingTypeDescription.some(
  248. .generic(
  249. wrapper: .member("MessageSerializer"),
  250. wrapped: .member(
  251. self.methodInputOutputTypealias(for: method, service: service, type: .input)
  252. )
  253. )
  254. )
  255. )
  256. }
  257. private func deserializerParameter(
  258. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  259. in service: CodeGenerationRequest.ServiceDescriptor
  260. ) -> ParameterDescription {
  261. return ParameterDescription(
  262. label: "deserializer",
  263. type: ExistingTypeDescription.some(
  264. .generic(
  265. wrapper: .member("MessageDeserializer"),
  266. wrapped: .member(
  267. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  268. )
  269. )
  270. )
  271. )
  272. }
  273. private func bodyParameter(
  274. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  275. in service: CodeGenerationRequest.ServiceDescriptor
  276. ) -> ParameterDescription {
  277. let clientStreaming = method.isOutputStreaming ? "Stream" : "Single"
  278. let closureParameterType = ExistingTypeDescription.generic(
  279. wrapper: .member(["ClientResponse", clientStreaming]),
  280. wrapped: .member(
  281. self.methodInputOutputTypealias(for: method, service: service, type: .output)
  282. )
  283. )
  284. let bodyClosure = ClosureSignatureDescription(
  285. parameters: [.init(type: closureParameterType)],
  286. keywords: [.async, .throws],
  287. returnType: .identifierType(.member("R")),
  288. sendable: true,
  289. escaping: true
  290. )
  291. return ParameterDescription(name: "body", type: .closure(bodyClosure))
  292. }
  293. private func makeClientStruct(
  294. for service: CodeGenerationRequest.ServiceDescriptor,
  295. in codeGenerationRequest: CodeGenerationRequest
  296. ) -> Declaration {
  297. let clientProperty = Declaration.variable(
  298. accessModifier: .private,
  299. kind: .let,
  300. left: "client",
  301. type: .member(["GRPCCore", "GRPCClient"])
  302. )
  303. let initializer = self.makeClientVariable()
  304. let methods = service.methods.map {
  305. Declaration.commentable(
  306. .doc($0.documentation),
  307. self.makeClientMethod(for: $0, in: service, from: codeGenerationRequest)
  308. )
  309. }
  310. return .struct(
  311. StructDescription(
  312. accessModifier: self.accessModifier,
  313. name: "\(service.namespacedPrefix)Client",
  314. conformances: ["\(service.namespacedTypealiasPrefix).ClientProtocol"],
  315. members: [clientProperty, initializer] + methods
  316. )
  317. )
  318. }
  319. private func makeClientVariable() -> Declaration {
  320. let initializerBody = Expression.assignment(
  321. left: .memberAccess(
  322. MemberAccessDescription(left: .identifierPattern("self"), right: "client")
  323. ),
  324. right: .identifierPattern("client")
  325. )
  326. return .function(
  327. signature: .init(
  328. accessModifier: self.accessModifier,
  329. kind: .initializer,
  330. parameters: [.init(label: "client", type: .member(["GRPCCore", "GRPCClient"]))]
  331. ),
  332. body: [CodeBlock(item: .expression(initializerBody))]
  333. )
  334. }
  335. private func clientMethod(
  336. isInputStreaming: Bool,
  337. isOutputStreaming: Bool
  338. ) -> String {
  339. switch (isInputStreaming, isOutputStreaming) {
  340. case (true, true):
  341. return "bidirectionalStreaming"
  342. case (true, false):
  343. return "clientStreaming"
  344. case (false, true):
  345. return "serverStreaming"
  346. case (false, false):
  347. return "unary"
  348. }
  349. }
  350. private func makeClientMethod(
  351. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  352. in service: CodeGenerationRequest.ServiceDescriptor,
  353. from codeGenerationRequest: CodeGenerationRequest
  354. ) -> Declaration {
  355. let parameters = self.makeParameters(
  356. for: method,
  357. in: service,
  358. from: codeGenerationRequest,
  359. generateSerializerDeserializer: false
  360. )
  361. let grpcMethodName = self.clientMethod(
  362. isInputStreaming: method.isInputStreaming,
  363. isOutputStreaming: method.isOutputStreaming
  364. )
  365. let functionCall = Expression.functionCall(
  366. calledExpression: .memberAccess(
  367. MemberAccessDescription(left: .identifierPattern("self.client"), right: "\(grpcMethodName)")
  368. ),
  369. arguments: [
  370. .init(label: "request", expression: .identifierPattern("request")),
  371. .init(
  372. label: "descriptor",
  373. expression: .identifierPattern(
  374. "\(service.namespacedTypealiasPrefix).Methods.\(method.name).descriptor"
  375. )
  376. ),
  377. .init(label: "serializer", expression: .identifierPattern("serializer")),
  378. .init(label: "deserializer", expression: .identifierPattern("deserializer")),
  379. .init(label: "handler", expression: .identifierPattern("body")),
  380. ]
  381. )
  382. let body = UnaryKeywordDescription(
  383. kind: .try,
  384. expression: .unaryKeyword(kind: .await, expression: functionCall)
  385. )
  386. return .function(
  387. accessModifier: self.accessModifier,
  388. kind: .function(
  389. name: "\(method.name)",
  390. isStatic: false
  391. ),
  392. generics: [.member("R")],
  393. parameters: parameters,
  394. keywords: [.async, .throws],
  395. returnType: .identifierType(.member("R")),
  396. whereClause: WhereClause(requirements: [.conformance("R", "Sendable")]),
  397. body: [.expression(.unaryKeyword(body))]
  398. )
  399. }
  400. fileprivate enum InputOutputType {
  401. case input
  402. case output
  403. }
  404. /// Generates the fully qualified name of the typealias for the input or output type of a method.
  405. private func methodInputOutputTypealias(
  406. for method: CodeGenerationRequest.ServiceDescriptor.MethodDescriptor,
  407. service: CodeGenerationRequest.ServiceDescriptor,
  408. type: InputOutputType
  409. ) -> String {
  410. var components: String = "\(service.namespacedTypealiasPrefix).Methods.\(method.name)"
  411. switch type {
  412. case .input:
  413. components.append(".Input")
  414. case .output:
  415. components.append(".Output")
  416. }
  417. return components
  418. }
  419. }