Avatar
protocol Cleanup { func cleanup() } macro(contexts: [.statement], external: "MyMacros.LocalCleanup") func localCleanup<Value: Cleanup>(_ varName: String, _ initializer: Value) --- #localCleanup("file", File(opening: "hello.txt")) --- let file = File(opening: "hello.txt") defer { file.cleanup() } (edited)
6:19 AM
defer生み出せるの面白いな。moveonly typeがあれば要らないマクロですが・・・
6:22 AM
// In the standard library extension Equatable { macro(contexts: [.conformance], external: "MyMacros.EquatableSynthesis") static func ==(lhs: Self, rhs: Self) -> Bool } // In the macro definition library struct EquatableSynthesis: ConformanceMacro { public static func apply( conformingType: TypeDecl, protocol: ProtocolDecl, witness: FunctionDeclSyntax, in context: MacroEvaluationContext ) -> (FunctionDeclSyntax, [Diagnostic]) { let comparisons: [ExprSyntax] = conformingType.storedProperties.map { property in "lhs.\(property.name) == rhs.\(property.name)" } let comparisonExpr: ExprSyntax = comparisons.map { $0.description }.joined(separator: " && ") return witness.withBody( """ { return \(comparisonExpr) } """ ) } }
6:22 AM
この TypeDecl は今無いやつだ、めっちゃ欲しい
6:23 AM
無いので自作してるやつ