ClientCodeTranslator.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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" with input type "Input" and output type "Output", 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>(
  27. /// request: GRPCCore.ClientRequest<Foo_Bar_Input>,
  28. /// serializer: some GRPCCore.MessageSerializer<Foo_Bar_Input>,
  29. /// deserializer: some GRPCCore.MessageDeserializer<Foo_Bar_Output>,
  30. /// options: GRPCCore.CallOptions = .defaults,
  31. /// _ body: @Sendable @escaping (GRPCCore.ClientResponse<Foo_Bar_Output>) async throws -> R
  32. /// ) async throws -> R where R: Sendable
  33. /// }
  34. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  35. /// extension Foo_Bar.ClientProtocol {
  36. /// public func baz<R>(
  37. /// request: GRPCCore.ClientRequest<Foo_Bar_Input>,
  38. /// options: GRPCCore.CallOptions = .defaults,
  39. /// _ body: @Sendable @escaping (GRPCCore.ClientResponse<Foo_Bar_Output>) async throws -> R = {
  40. /// try $0.message
  41. /// }
  42. /// ) async throws -> R where R: Sendable {
  43. /// try await self.baz(
  44. /// request: request,
  45. /// serializer: GRPCProtobuf.ProtobufSerializer<Foo_Bar_Input>(),
  46. /// deserializer: GRPCProtobuf.ProtobufDeserializer<Foo_Bar_Output>(),
  47. /// options: options,
  48. /// body
  49. /// )
  50. /// }
  51. /// @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  52. /// public struct Foo_BarClient: Foo_Bar.ClientProtocol {
  53. /// private let client: GRPCCore.GRPCClient
  54. /// public init(wrapping client: GRPCCore.GRPCClient) {
  55. /// self.client = client
  56. /// }
  57. /// public func methodA<R>(
  58. /// request: GRPCCore.StreamingClientRequest<Foo_Bar_Input>,
  59. /// serializer: some GRPCCore.MessageSerializer<Foo_Bar_Input>,
  60. /// deserializer: some GRPCCore.MessageDeserializer<Foo_Bar_Output>,
  61. /// options: GRPCCore.CallOptions = .defaults,
  62. /// _ body: @Sendable @escaping (GRPCCore.ClientResponse<Foo_Bar_Output>) async throws -> R = {
  63. /// try $0.message
  64. /// }
  65. /// ) async throws -> R where R: Sendable {
  66. /// try await self.client.unary(
  67. /// request: request,
  68. /// descriptor: NamespaceA.ServiceA.Method.MethodA.descriptor,
  69. /// serializer: serializer,
  70. /// deserializer: deserializer,
  71. /// options: options,
  72. /// handler: body
  73. /// )
  74. /// }
  75. /// }
  76. ///```
  77. @available(gRPCSwift 2.0, *)
  78. struct ClientCodeTranslator {
  79. init() {}
  80. func translate(
  81. accessModifier: AccessModifier,
  82. service: ServiceDescriptor,
  83. availability: AvailabilityDescription,
  84. namer: Namer = Namer(),
  85. serializer: (String) -> String,
  86. deserializer: (String) -> String
  87. ) -> [CodeBlock] {
  88. var blocks = [CodeBlock]()
  89. let `extension` = ExtensionDescription(
  90. onType: service.name.typeName,
  91. declarations: [
  92. // protocol ClientProtocol { ... }
  93. .commentable(
  94. .preFormatted(
  95. Docs.suffix(
  96. self.clientProtocolDocs(serviceName: service.name.identifyingName),
  97. withDocs: service.documentation
  98. )
  99. ),
  100. .protocol(
  101. .clientProtocol(
  102. accessLevel: accessModifier,
  103. name: "ClientProtocol",
  104. methods: service.methods,
  105. namer: namer
  106. )
  107. )
  108. ),
  109. // struct Client: ClientProtocol { ... }
  110. .commentable(
  111. .preFormatted(
  112. Docs.suffix(
  113. self.clientDocs(
  114. serviceName: service.name.identifyingName,
  115. moduleName: namer.grpcCore
  116. ),
  117. withDocs: service.documentation
  118. )
  119. ),
  120. .struct(
  121. .client(
  122. accessLevel: accessModifier,
  123. name: "Client",
  124. serviceEnum: service.name.typeName,
  125. clientProtocol: "ClientProtocol",
  126. methods: service.methods,
  127. namer: namer
  128. )
  129. )
  130. ),
  131. ]
  132. )
  133. blocks.append(.declaration(.guarded(availability, .extension(`extension`))))
  134. let extensionWithDefaults: ExtensionDescription = .clientMethodSignatureWithDefaults(
  135. accessLevel: accessModifier,
  136. name: "\(service.name.typeName).ClientProtocol",
  137. methods: service.methods,
  138. namer: namer,
  139. serializer: serializer,
  140. deserializer: deserializer
  141. )
  142. blocks.append(
  143. CodeBlock(
  144. comment: .inline("Helpers providing default arguments to 'ClientProtocol' methods."),
  145. item: .declaration(.guarded(availability, .extension(extensionWithDefaults)))
  146. )
  147. )
  148. let extensionWithExplodedAPI: ExtensionDescription = .explodedClientMethods(
  149. accessLevel: accessModifier,
  150. on: "\(service.name.typeName).ClientProtocol",
  151. methods: service.methods,
  152. namer: namer
  153. )
  154. blocks.append(
  155. CodeBlock(
  156. comment: .inline("Helpers providing sugared APIs for 'ClientProtocol' methods."),
  157. item: .declaration(.guarded(availability, .extension(extensionWithExplodedAPI)))
  158. )
  159. )
  160. return blocks
  161. }
  162. private func clientProtocolDocs(serviceName: String) -> String {
  163. return """
  164. /// Generated client protocol for the "\(serviceName)" service.
  165. ///
  166. /// You don't need to implement this protocol directly, use the generated
  167. /// implementation, ``Client``.
  168. """
  169. }
  170. private func clientDocs(serviceName: String, moduleName: String) -> String {
  171. return """
  172. /// Generated client for the "\(serviceName)" service.
  173. ///
  174. /// The ``Client`` provides an implementation of ``ClientProtocol`` which wraps
  175. /// a `\(moduleName).GRPCCClient`. The underlying `GRPCClient` provides the long-lived
  176. /// means of communication with the remote peer.
  177. """
  178. }
  179. }