Swift宏未覆盖声明名

g2ieeal7  于 2023-06-21  发布在  Swift
关注(0)|答案(1)|浏览(160)

我正在摆弄新的Swift 5.9宏。
我有以下宏:
给定以下枚举

@associatedValues
enum Fruit {
    case banana(Banana)
    case grape(Grape)
}

我想要

@associatedValues
enum Fruit {
    case banana(Banana)
    case grape(Grape)

    var bananaValue: Banana? { if ... return ... } }
    var grapeValue: Grape? { if ... return ... } }
}

我的实现是这样的:

public static func expansion<Declaration, Context>(
        of node: SwiftSyntax.AttributeSyntax,
        providingMembersOf declaration: Declaration,
        in context: Context
    ) throws -> [SwiftSyntax.DeclSyntax]
    where Declaration: SwiftSyntax.DeclGroupSyntax,
          Context: SwiftSyntaxMacros.MacroExpansionContext
    {
        
        guard let enumDeclaration = declaration.as(EnumDeclSyntax.self) else {
            throw AssociatedValuesMacroError.onlyApplicableToEnum
        }
        
        return enumDeclaration.memberBlock.members
            .compactMap { $0.decl.as(EnumCaseDeclSyntax.self) }
            .map { (_case: EnumCaseDeclSyntax) in

                let _element: EnumCaseElementListSyntax.Element = _case.elements.first!
                let caseName = _element.identifier
                let typeName = _element.associatedValue!.parameterList.first!.description

                return
                    """
                    var \(raw: caseName)Value: \(raw: typeName)? {
                        if case let .\(raw: caseName)(value) = self {
                            return value
                        } else {
                            return nil
                        }
                    }
                    """
            }
    }

现在,自动完成检测到新的属性,但编译器告诉我:
Declaration name 'bananaValue' is not covered by macro 'associatedValues'
Declaration name 'grapeValue' is not covered by macro 'associatedValues'
测试运行并验证输出,但不是在编译时。

我错过了什么?谢谢你

bjp0bcyl

bjp0bcyl1#

我们需要将names: arbitrary添加到宏角色。

@attached(member, names: arbitrary)
public macro AssociatedValues() = #externalMacro(module: "MyMacrosModule", type: "AssociatedValuesMacro")

此外,虽然不是对特定问题的回答,但请确保将宏类型添加到CompilerPlugin中提供宏的列表中。

#if canImport(SwiftCompilerPlugin)
import SwiftCompilerPlugin
import SwiftSyntaxMacros

@main
struct MacrosPlugin: CompilerPlugin {
  let providingMacros: [Macro.Type] = [
      AssociatedValueMacro.self
  ]
}

相关问题