Created
June 14, 2023 02:49
-
-
Save griotspeak/5dfd7c99d25b08f812c5dbe68e80fa27 to your computer and use it in GitHub Desktop.
Equatable for Nuno
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// The Swift Programming Language | |
// https://docs.swift.org/swift-book | |
@attached(conformance) | |
public macro Equatable() = #externalMacro( | |
module: "EquatableMacros", | |
type: "EquatableMacro" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Equatable | |
@Equatable | |
struct SomeStruct { } | |
let a = SomeStruct() | |
let b = SomeStruct() | |
print(a == b) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftCompilerPlugin | |
import SwiftSyntax | |
import SwiftSyntaxBuilder | |
import SwiftSyntaxMacros | |
public struct EquatableMacro: ConformanceMacro { | |
public static func expansion( | |
of node: AttributeSyntax, | |
providingConformancesOf decl: some DeclGroupSyntax, | |
in context: some MacroExpansionContext | |
) throws -> [(TypeSyntax, GenericWhereClauseSyntax?)] { | |
let protocolName: TypeSyntax = "Equatable" | |
return [(protocolName, nil)] | |
} | |
enum Error: Swift.Error { | |
case print(String) | |
} | |
} | |
@main | |
struct EquatableMacroPlugin: CompilerPlugin { | |
let providingMacros: [Macro.Type] = [ | |
EquatableMacro.self, | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import SwiftSyntaxMacros | |
import SwiftSyntaxMacrosTestSupport | |
import XCTest | |
import EquatableMacros | |
let testMacros: [String: Macro.Type] = [ | |
"Equatable": EquatableMacro.self, | |
] | |
final class EquatableTests: XCTestCase { | |
func testMacro() { | |
assertMacroExpansion( | |
""" | |
@Equatable____ | |
class XXX {} | |
""", | |
expandedSource: """ | |
""", | |
macros: testMacros | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment