IDLToStructuredSwiftTranslator.swift 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 servicesByUpperCaseNamespace = Dictionary(
  95. grouping: codeGenerationRequest.services,
  96. by: { $0.namespace.generatedUpperCase }
  97. )
  98. try self.checkServiceNamesAreUnique(for: servicesByUpperCaseNamespace)
  99. for service in codeGenerationRequest.services {
  100. try self.checkMethodNamesAreUnique(in: service)
  101. }
  102. }
  103. // Verify service names are unique within each namespace and that services with no namespace
  104. // don't have the same names as any of the namespaces.
  105. private func checkServiceNamesAreUnique(
  106. for servicesByUpperCaseNamespace: [String: [CodeGenerationRequest.ServiceDescriptor]]
  107. ) throws {
  108. // Check that if there are services in an empty namespace, none have names which match other namespaces,
  109. // to ensure that there are no enums with the same name in the type aliases part of the generated code.
  110. if let noNamespaceServices = servicesByUpperCaseNamespace[""] {
  111. let upperCaseNamespaces = servicesByUpperCaseNamespace.keys
  112. for service in noNamespaceServices {
  113. if upperCaseNamespaces.contains(service.name.generatedUpperCase) {
  114. throw CodeGenError(
  115. code: .nonUniqueServiceName,
  116. message: """
  117. Services with no namespace must not have the same generated upper case names as the namespaces. \
  118. \(service.name.generatedUpperCase) is used as a generated upper case name for a service with no namespace and a namespace.
  119. """
  120. )
  121. }
  122. }
  123. }
  124. // Check that the generated upper case names for services are unique within each namespace, to ensure that
  125. // the service enums from each namespace enum have unique names.
  126. for (namespace, services) in servicesByUpperCaseNamespace {
  127. var upperCaseNames: Set<String> = []
  128. for service in services {
  129. if upperCaseNames.contains(service.name.generatedUpperCase) {
  130. let errorMessage: String
  131. if namespace.isEmpty {
  132. errorMessage = """
  133. Services in an empty namespace must have unique generated upper case names. \
  134. \(service.name.generatedUpperCase) is used as a generated upper case name for multiple services without namespaces.
  135. """
  136. } else {
  137. errorMessage = """
  138. Services within the same namespace must have unique generated upper case names. \
  139. \(service.name.generatedUpperCase) is used as a generated upper case name for multiple services in the \(service.namespace.base) namespace.
  140. """
  141. }
  142. throw CodeGenError(
  143. code: .nonUniqueServiceName,
  144. message: errorMessage
  145. )
  146. }
  147. upperCaseNames.insert(service.name.generatedUpperCase)
  148. }
  149. }
  150. }
  151. // Verify method names are unique within a service.
  152. private func checkMethodNamesAreUnique(
  153. in service: CodeGenerationRequest.ServiceDescriptor
  154. ) throws {
  155. // Check that the method descriptors are unique, by checking that the base names
  156. // of the methods of a specific service are unique.
  157. let baseNames = service.methods.map { $0.name.base }
  158. if let duplicatedBase = baseNames.getFirstDuplicate() {
  159. throw CodeGenError(
  160. code: .nonUniqueMethodName,
  161. message: """
  162. Methods of a service must have unique base names. \
  163. \(duplicatedBase) is used as a base name for multiple methods of the \(service.name.base) service.
  164. """
  165. )
  166. }
  167. // Check that generated upper case names for methods are unique within a service, to ensure that
  168. // the enums containing type aliases for each method of a service.
  169. let upperCaseNames = service.methods.map { $0.name.generatedUpperCase }
  170. if let duplicatedGeneratedUpperCase = upperCaseNames.getFirstDuplicate() {
  171. throw CodeGenError(
  172. code: .nonUniqueMethodName,
  173. message: """
  174. Methods of a service must have unique generated upper case names. \
  175. \(duplicatedGeneratedUpperCase) is used as a generated upper case name for multiple methods of the \(service.name.base) service.
  176. """
  177. )
  178. }
  179. // Check that generated lower case names for methods are unique within a service, to ensure that
  180. // the function declarations and definitions from the same protocols and extensions have unique names.
  181. let lowerCaseNames = service.methods.map { $0.name.generatedLowerCase }
  182. if let duplicatedLowerCase = lowerCaseNames.getFirstDuplicate() {
  183. throw CodeGenError(
  184. code: .nonUniqueMethodName,
  185. message: """
  186. Methods of a service must have unique lower case names. \
  187. \(duplicatedLowerCase) is used as a signature name for multiple methods of the \(service.name.base) service.
  188. """
  189. )
  190. }
  191. }
  192. private func checkServiceDescriptorsAreUnique(
  193. _ services: [CodeGenerationRequest.ServiceDescriptor]
  194. ) throws {
  195. var descriptors: Set<String> = []
  196. for service in services {
  197. let name =
  198. service.namespace.base.isEmpty
  199. ? service.name.base : "\(service.namespace.base).\(service.name.base)"
  200. let (inserted, _) = descriptors.insert(name)
  201. if !inserted {
  202. throw CodeGenError(
  203. code: .nonUniqueServiceName,
  204. message: """
  205. Services must have unique descriptors. \
  206. \(name) is the descriptor of at least two different services.
  207. """
  208. )
  209. }
  210. }
  211. }
  212. }
  213. extension CodeGenerationRequest.ServiceDescriptor {
  214. var namespacedTypealiasGeneratedName: String {
  215. if self.namespace.generatedUpperCase.isEmpty {
  216. return self.name.generatedUpperCase
  217. } else {
  218. return "\(self.namespace.generatedUpperCase).\(self.name.generatedUpperCase)"
  219. }
  220. }
  221. var namespacedGeneratedName: String {
  222. if self.namespace.generatedUpperCase.isEmpty {
  223. return self.name.generatedUpperCase
  224. } else {
  225. return "\(self.namespace.generatedUpperCase)_\(self.name.generatedUpperCase)"
  226. }
  227. }
  228. var fullyQualifiedName: String {
  229. if self.namespace.base.isEmpty {
  230. return self.name.base
  231. } else {
  232. return "\(self.namespace.base).\(self.name.base)"
  233. }
  234. }
  235. }
  236. extension [String] {
  237. internal func getFirstDuplicate() -> String? {
  238. var seen = Set<String>()
  239. for element in self {
  240. if seen.contains(element) {
  241. return element
  242. }
  243. seen.insert(element)
  244. }
  245. return nil
  246. }
  247. }