AutoCodableMacro.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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. // 过滤计算属性
  52. guard binding.accessorBlock == nil else {
  53. return nil
  54. }
  55. // 3. 提取属性名称
  56. guard let identifierPattern = binding.pattern.as(IdentifierPatternSyntax.self) else {
  57. return nil
  58. }
  59. let name = identifierPattern.identifier.text
  60. // 4. 提取属性类型
  61. guard let typeAnnotation = binding.typeAnnotation else {
  62. return nil
  63. }
  64. let type = typeAnnotation.type.description.trimmingCharacters(in: .whitespacesAndNewlines)
  65. return (name: name, type: type)
  66. }
  67. if properties.isEmpty {
  68. context.diagnose(
  69. Diagnostic(
  70. node: node,
  71. message: AutoCodableMacroError.noStoredProperties
  72. )
  73. )
  74. }
  75. var syntax: [DeclSyntax] = []
  76. // 生成 CodingKeys 枚举
  77. let codingKeys = try EnumDeclSyntax("enum CodingKeys: String, CodingKey") {
  78. for property in properties {
  79. DeclSyntax("case \(raw: property.name)")
  80. }
  81. }
  82. syntax.append(DeclSyntax(codingKeys))
  83. if conformsToDecodable {
  84. // 生成 init(from:) 方法
  85. let bodyBuilder: SyntaxNodeString = declaration is ClassDeclSyntax ? "required init(from decoder: Decoder) throws" : "init(from decoder: Decoder) throws"
  86. let initFrom = try InitializerDeclSyntax(bodyBuilder) {
  87. CodeBlockItemListSyntax {
  88. "let container = try decoder.container(keyedBy: CodingKeys.self)"
  89. for property in properties {
  90. """
  91. if let value = try? container.decode(\(raw: property.type).self, forKey: .\(raw: property.name)) {
  92. self.\(raw: property.name) = value
  93. }
  94. """
  95. }
  96. }
  97. }
  98. syntax.append(DeclSyntax(initFrom))
  99. }
  100. if conformsToEncodable {
  101. // 生成 encode(to:) 方法
  102. let encodeTo = try FunctionDeclSyntax("func encode(to encoder: Encoder) throws") {
  103. CodeBlockItemListSyntax {
  104. "var container = encoder.container(keyedBy: CodingKeys.self)"
  105. for property in properties {
  106. "try container.encode(\(raw: property.name), forKey: .\(raw: property.name))"
  107. }
  108. }
  109. }
  110. syntax.append(DeclSyntax(encodeTo))
  111. }
  112. return syntax
  113. }
  114. }
  115. // 错误提示定义
  116. enum AutoCodableMacroError: DiagnosticMessage {
  117. case onlyClassesAndStructs
  118. case noStoredProperties
  119. case protocolError
  120. var message: String {
  121. switch self {
  122. case .onlyClassesAndStructs:
  123. "AutoCodable can only be applied to classes and structs"
  124. case .noStoredProperties:
  125. "Type has no stored properties; Codable implementation will be empty"
  126. case .protocolError:
  127. "类型必须遵循 Codable、Decodable 或 Encodable"
  128. }
  129. }
  130. var diagnosticID: MessageID { .init(domain: "Codable", id: "\(self)") }
  131. var severity: DiagnosticSeverity { .error }
  132. }