ClientCodeTranslator.swift 16 KB

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