2
0

IDLToStructuredSwiftTranslator.swift 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 server and client code, as well as for the enums containing useful type aliases and properties.
  17. /// The representation is generated based on the ``CodeGenerationRequest`` object and user specifications,
  18. /// using types from ``StructuredSwiftRepresentation``.
  19. struct IDLToStructuredSwiftTranslator: Translator {
  20. func translate(
  21. codeGenerationRequest: CodeGenerationRequest,
  22. accessLevel: SourceGenerator.Configuration.AccessLevel,
  23. client: Bool,
  24. server: Bool
  25. ) throws -> StructuredSwiftRepresentation {
  26. try self.validateInput(codeGenerationRequest)
  27. let typealiasTranslator = TypealiasTranslator(
  28. client: client,
  29. server: server,
  30. accessLevel: accessLevel
  31. )
  32. let topComment = Comment.preFormatted(codeGenerationRequest.leadingTrivia)
  33. let imports = try codeGenerationRequest.dependencies.reduce(
  34. into: [ImportDescription(moduleName: "GRPCCore")]
  35. ) { partialResult, newDependency in
  36. try partialResult.append(translateImport(dependency: newDependency))
  37. }
  38. var codeBlocks = [CodeBlock]()
  39. codeBlocks.append(
  40. contentsOf: try typealiasTranslator.translate(from: codeGenerationRequest)
  41. )
  42. if server {
  43. let serverCodeTranslator = ServerCodeTranslator(accessLevel: accessLevel)
  44. codeBlocks.append(
  45. contentsOf: try serverCodeTranslator.translate(from: codeGenerationRequest)
  46. )
  47. }
  48. if client {
  49. let clientCodeTranslator = ClientCodeTranslator(accessLevel: accessLevel)
  50. codeBlocks.append(
  51. contentsOf: try clientCodeTranslator.translate(from: codeGenerationRequest)
  52. )
  53. }
  54. let fileDescription = FileDescription(
  55. topComment: topComment,
  56. imports: imports,
  57. codeBlocks: codeBlocks
  58. )
  59. let fileName = String(codeGenerationRequest.fileName.split(separator: ".")[0])
  60. let file = NamedFileDescription(name: fileName, contents: fileDescription)
  61. return StructuredSwiftRepresentation(file: file)
  62. }
  63. }
  64. extension IDLToStructuredSwiftTranslator {
  65. private func translateImport(
  66. dependency: CodeGenerationRequest.Dependency
  67. ) throws -> ImportDescription {
  68. var importDescription = ImportDescription(moduleName: dependency.module)
  69. if let item = dependency.item {
  70. if let matchedKind = ImportDescription.Kind(rawValue: item.kind.value.rawValue) {
  71. importDescription.item = ImportDescription.Item(kind: matchedKind, name: item.name)
  72. } else {
  73. throw CodeGenError(
  74. code: .invalidKind,
  75. message: "Invalid kind name for import: \(item.kind.value.rawValue)"
  76. )
  77. }
  78. }
  79. if let spi = dependency.spi {
  80. importDescription.spi = spi
  81. }
  82. switch dependency.preconcurrency.value {
  83. case .required:
  84. importDescription.preconcurrency = .always
  85. case .notRequired:
  86. importDescription.preconcurrency = .never
  87. case .requiredOnOS(let OSs):
  88. importDescription.preconcurrency = .onOS(OSs)
  89. }
  90. return importDescription
  91. }
  92. private func validateInput(_ codeGenerationRequest: CodeGenerationRequest) throws {
  93. try self.checkServiceDescriptorsAreUnique(codeGenerationRequest.services)
  94. let servicesByGeneratedEnumName = Dictionary(
  95. grouping: codeGenerationRequest.services,
  96. by: { $0.namespacedGeneratedName }
  97. )
  98. try self.checkServiceEnumNamesAreUnique(for: servicesByGeneratedEnumName)
  99. for service in codeGenerationRequest.services {
  100. try self.checkMethodNamesAreUnique(in: service)
  101. }
  102. }
  103. // Verify service enum names are unique.
  104. private func checkServiceEnumNamesAreUnique(
  105. for servicesByGeneratedEnumName: [String: [CodeGenerationRequest.ServiceDescriptor]]
  106. ) throws {
  107. for (generatedEnumName, services) in servicesByGeneratedEnumName {
  108. if services.count > 1 {
  109. throw CodeGenError(
  110. code: .nonUniqueServiceName,
  111. message: """
  112. There must be a unique (namespace, service_name) pair for each service. \
  113. \(generatedEnumName) is used as a <namespace>_<service_name> construction for multiple services.
  114. """
  115. )
  116. }
  117. }
  118. }
  119. // Verify method names are unique within a service.
  120. private func checkMethodNamesAreUnique(
  121. in service: CodeGenerationRequest.ServiceDescriptor
  122. ) throws {
  123. // Check that the method descriptors are unique, by checking that the base names
  124. // of the methods of a specific service are unique.
  125. let baseNames = service.methods.map { $0.name.base }
  126. if let duplicatedBase = baseNames.getFirstDuplicate() {
  127. throw CodeGenError(
  128. code: .nonUniqueMethodName,
  129. message: """
  130. Methods of a service must have unique base names. \
  131. \(duplicatedBase) is used as a base name for multiple methods of the \(service.name.base) service.
  132. """
  133. )
  134. }
  135. // Check that generated upper case names for methods are unique within a service, to ensure that
  136. // the enums containing type aliases for each method of a service.
  137. let upperCaseNames = service.methods.map { $0.name.generatedUpperCase }
  138. if let duplicatedGeneratedUpperCase = upperCaseNames.getFirstDuplicate() {
  139. throw CodeGenError(
  140. code: .nonUniqueMethodName,
  141. message: """
  142. Methods of a service must have unique generated upper case names. \
  143. \(duplicatedGeneratedUpperCase) is used as a generated upper case name for multiple methods of the \(service.name.base) service.
  144. """
  145. )
  146. }
  147. // Check that generated lower case names for methods are unique within a service, to ensure that
  148. // the function declarations and definitions from the same protocols and extensions have unique names.
  149. let lowerCaseNames = service.methods.map { $0.name.generatedLowerCase }
  150. if let duplicatedLowerCase = lowerCaseNames.getFirstDuplicate() {
  151. throw CodeGenError(
  152. code: .nonUniqueMethodName,
  153. message: """
  154. Methods of a service must have unique lower case names. \
  155. \(duplicatedLowerCase) is used as a signature name for multiple methods of the \(service.name.base) service.
  156. """
  157. )
  158. }
  159. }
  160. private func checkServiceDescriptorsAreUnique(
  161. _ services: [CodeGenerationRequest.ServiceDescriptor]
  162. ) throws {
  163. var descriptors: Set<String> = []
  164. for service in services {
  165. let name =
  166. service.namespace.base.isEmpty
  167. ? service.name.base : "\(service.namespace.base).\(service.name.base)"
  168. let (inserted, _) = descriptors.insert(name)
  169. if !inserted {
  170. throw CodeGenError(
  171. code: .nonUniqueServiceName,
  172. message: """
  173. Services must have unique descriptors. \
  174. \(name) is the descriptor of at least two different services.
  175. """
  176. )
  177. }
  178. }
  179. }
  180. }
  181. extension CodeGenerationRequest.ServiceDescriptor {
  182. var namespacedGeneratedName: String {
  183. if self.namespace.generatedUpperCase.isEmpty {
  184. return self.name.generatedUpperCase
  185. } else {
  186. return "\(self.namespace.generatedUpperCase)_\(self.name.generatedUpperCase)"
  187. }
  188. }
  189. var fullyQualifiedName: String {
  190. if self.namespace.base.isEmpty {
  191. return self.name.base
  192. } else {
  193. return "\(self.namespace.base).\(self.name.base)"
  194. }
  195. }
  196. }
  197. extension [String] {
  198. internal func getFirstDuplicate() -> String? {
  199. var seen = Set<String>()
  200. for element in self {
  201. if seen.contains(element) {
  202. return element
  203. }
  204. seen.insert(element)
  205. }
  206. return nil
  207. }
  208. }