IDLToStructuredSwiftTranslator.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. struct IDLToStructuredSwiftTranslator: Translator {
  17. private let typealiasTranslator = TypealiasTranslator()
  18. private let serverCodeTranslator = ServerCodeTranslator()
  19. func translate(
  20. codeGenerationRequest: CodeGenerationRequest,
  21. client: Bool,
  22. server: Bool
  23. ) throws -> StructuredSwiftRepresentation {
  24. let topComment = Comment.doc(codeGenerationRequest.leadingTrivia)
  25. let imports: [ImportDescription] = [
  26. ImportDescription(moduleName: "GRPCCore")
  27. ]
  28. var codeBlocks: [CodeBlock] = []
  29. codeBlocks.append(
  30. contentsOf: try self.typealiasTranslator.translate(from: codeGenerationRequest)
  31. )
  32. if server {
  33. codeBlocks.append(
  34. contentsOf: try self.serverCodeTranslator.translate(from: codeGenerationRequest)
  35. )
  36. }
  37. let fileDescription = FileDescription(
  38. topComment: topComment,
  39. imports: imports,
  40. codeBlocks: codeBlocks
  41. )
  42. let fileName = String(codeGenerationRequest.fileName.split(separator: ".")[0])
  43. let file = NamedFileDescription(name: fileName, contents: fileDescription)
  44. return StructuredSwiftRepresentation(file: file)
  45. }
  46. }
  47. extension CodeGenerationRequest.ServiceDescriptor {
  48. var namespacedTypealiasPrefix: String {
  49. if self.namespace.isEmpty {
  50. return self.name
  51. } else {
  52. return "\(self.namespace).\(self.name)"
  53. }
  54. }
  55. var namespacedPrefix: String {
  56. if self.namespace.isEmpty {
  57. return self.name
  58. } else {
  59. return "\(self.namespace)_\(self.name)"
  60. }
  61. }
  62. }