Skip to content

Instantly share code, notes, and snippets.

@MasterJ93
Created August 27, 2024 01:21
Show Gist options
  • Save MasterJ93/42977c351b394e05128d1f800a15e086 to your computer and use it in GitHub Desktop.
Save MasterJ93/42977c351b394e05128d1f800a15e086 to your computer and use it in GitHub Desktop.
Currently working Swift macro that deals with a dictionary (`DictionaryElementListSyntax`, `DictionaryExprSyntax`)
// Macro signature
@freestanding(declaration, names: arbitrary)
public macro ExperimentMacro(_ named: String, contains: [String: String]) = #externalMacro(module: "ExperimentMacroMacros", type: "ExperimentMacro")
// 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