我正在摆弄新的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'
测试运行并验证输出,但不是在编译时。
我错过了什么?谢谢你
1条答案
按热度按时间bjp0bcyl1#
我们需要将
names: arbitrary
添加到宏角色。此外,虽然不是对特定问题的回答,但请确保将宏类型添加到
CompilerPlugin
中提供宏的列表中。