Created
August 27, 2024 01:21
-
-
Save MasterJ93/42977c351b394e05128d1f800a15e086 to your computer and use it in GitHub Desktop.
Currently working Swift macro that deals with a dictionary (`DictionaryElementListSyntax`, `DictionaryExprSyntax`)
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
// Macro signature | |
@freestanding(declaration, names: arbitrary) | |
public macro ExperimentMacro(_ named: String, contains: [String: String]) = #externalMacro(module: "ExperimentMacroMacros", type: "ExperimentMacro") |
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
// Implementation | |
import SwiftCompilerPlugin | |
import SwiftSyntax | |
import SwiftSyntaxBuilder | |
import SwiftSyntaxMacros | |
public struct ExperimentMacro: DeclarationMacro { | |
public static func expansion( | |
of node: some FreestandingMacroExpansionSyntax, | |
in context: some MacroExpansionContext | |
) throws -> [DeclSyntax] { | |
guard let argument = node.argumentList.as(LabeledExprListSyntax.self), | |
argument.count > 0 else { | |
fatalError("No cases") | |
} | |
let string = argument | |
.children(viewMode: .all) | |
.compactMap { $0.as(LabeledExprSyntax.self) } | |
.map(\.expression) | |
.compactMap { $0.as(StringLiteralExprSyntax.self) } | |
.map { String(describing: $0) } | |
let dictArray = argument | |
.children(viewMode: .all) | |
.compactMap { $0.as(LabeledExprSyntax.self) } | |
.map(\.expression)[1].cast(DictionaryExprSyntax.self).content | |
return [ | |
""" | |
public let stringTesting: [String] = \(raw: string) | |
public let dictTesting: String = \(literal: String(describing: dictArray)) | |
""" | |
] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment