AutoCodableMacro.swift 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // The Swift Programming Language
  2. // https://docs.swift.org/swift-book
  3. import SwiftSyntax
  4. import SwiftSyntaxBuilder
  5. import SwiftSyntaxMacros
  6. import SwiftDiagnostics
  7. import Foundation
  8. // 宏实现:自动生成 Codable 协议的实现
  9. public struct AutoCodableMacro: MemberMacro {
  10. public static func expansion(
  11. of node: AttributeSyntax,
  12. providingMembersOf declaration: some DeclGroupSyntax,
  13. in context: some MacroExpansionContext
  14. ) throws -> [DeclSyntax] {
  15. // 仅支持类和结构体
  16. guard let typeDecl: DeclGroupSyntax = declaration.as(ClassDeclSyntax.self) ?? declaration.as(StructDeclSyntax.self) else {
  17. context.diagnose(
  18. Diagnostic(
  19. node: node,
  20. message: AutoCodableMacroError.onlyClassesAndStructs
  21. )
  22. )
  23. return []
  24. }
  25. // 解析类型遵循的协议列表
  26. let inheritedProtocols = typeDecl.inheritanceClause?.inheritedTypes
  27. .compactMap { $0.type.as(IdentifierTypeSyntax.self)?.name.text } ?? []
  28. // 判断是否遵循 Codable/Decodable/Encodable
  29. let conformsToCodable = inheritedProtocols.contains("Codable")
  30. let conformsToDecodable = inheritedProtocols.contains("Decodable") || conformsToCodable
  31. let conformsToEncodable = inheritedProtocols.contains("Encodable") || conformsToCodable
  32. // 校验:至少遵循一个协议,否则报错
  33. guard conformsToDecodable || conformsToEncodable else {
  34. context.diagnose(Diagnostic(
  35. node: node,
  36. message: AutoCodableMacroError.protocolError
  37. ))
  38. return []
  39. }
  40. // 提取所有存储属性
  41. let properties: [(name: String, type: String)] = typeDecl.memberBlock.members.compactMap { member -> (name: String, type: String)? in
  42. // 1. 检查是否是变量声明
  43. guard let variableDecl = member.decl.as(VariableDeclSyntax.self) else {
  44. return nil
  45. }
  46. // 2. 确保只处理单个属性的声明
  47. guard variableDecl.bindings.count == 1,
  48. let binding = variableDecl.bindings.first else {
  49. return nil
  50. }
  51. // 3. 提取属性名称
  52. guard let identifierPattern = binding.pattern.as(IdentifierPatternSyntax.self) else {
  53. return nil
  54. }
  55. let name = identifierPattern.identifier.text
  56. // 4. 提取属性类型
  57. guard let typeAnnotation = binding.typeAnnotation else {
  58. return nil
  59. }
  60. let type = typeAnnotation.type.description.trimmingCharacters(in: .whitespacesAndNewlines)
  61. return (name: name, type: type)
  62. }
  63. if properties.isEmpty {
  64. context.diagnose(
  65. Diagnostic(
  66. node: node,
  67. message: AutoCodableMacroError.noStoredProperties
  68. )
  69. )
  70. }
  71. var syntax: [DeclSyntax] = []
  72. // 生成 CodingKeys 枚举
  73. let codingKeys = try EnumDeclSyntax("enum CodingKeys: String, CodingKey") {
  74. for property in properties {
  75. DeclSyntax("case \(raw: property.name)")
  76. }
  77. }
  78. syntax.append(DeclSyntax(codingKeys))
  79. if conformsToDecodable {
  80. // 生成 init(from:) 方法
  81. let bodyBuilder: SyntaxNodeString = declaration is ClassDeclSyntax ? "required init(from decoder: Decoder) throws" : "init(from decoder: Decoder) throws"
  82. let initFrom = try InitializerDeclSyntax(bodyBuilder) {
  83. CodeBlockItemListSyntax {
  84. "let container = try decoder.container(keyedBy: CodingKeys.self)"
  85. for property in properties {
  86. """
  87. if let value = try? container.decode(\(raw: property.type).self, forKey: .\(raw: property.name)) {
  88. self.\(raw: property.name) = value
  89. }
  90. """
  91. }
  92. }
  93. }
  94. syntax.append(DeclSyntax(initFrom))
  95. }
  96. if conformsToEncodable {
  97. // 生成 encode(to:) 方法
  98. let encodeTo = try FunctionDeclSyntax("func encode(to encoder: Encoder) throws") {
  99. CodeBlockItemListSyntax {
  100. "var container = encoder.container(keyedBy: CodingKeys.self)"
  101. for property in properties {
  102. "try container.encode(\(raw: property.name), forKey: .\(raw: property.name))"
  103. }
  104. }
  105. }
  106. syntax.append(DeclSyntax(encodeTo))
  107. }
  108. return syntax
  109. }
  110. }
  111. // 错误提示定义
  112. enum AutoCodableMacroError: DiagnosticMessage {
  113. case onlyClassesAndStructs
  114. case noStoredProperties
  115. case protocolError
  116. var message: String {
  117. switch self {
  118. case .onlyClassesAndStructs:
  119. "AutoCodable can only be applied to classes and structs"
  120. case .noStoredProperties:
  121. "Type has no stored properties; Codable implementation will be empty"
  122. case .protocolError:
  123. "类型必须遵循 Codable、Decodable 或 Encodable"
  124. }
  125. }
  126. var diagnosticID: MessageID { .init(domain: "Codable", id: "\(self)") }
  127. var severity: DiagnosticSeverity { .error }
  128. }