Files
swift-mirror/test/Macros/Inputs/syntax_macro_definitions.swift
Doug Gregor 5bd94d680e [Macros] Adapt to macro API changes and switch more testing to use it.
The API provided by macro evaluation has changed a bit. Adapt ASTGen to
the new API, and use this as an opportunity to start moving more tests
to using the shared libraries built into the toolchain.
2022-12-02 16:35:14 -08:00

57 lines
1.7 KiB
Swift

import SwiftSyntax
import SwiftSyntaxBuilder
import _SwiftSyntaxMacros
/// Replace the label of the first element in the tuple with the given
/// new label.
private func replaceFirstLabel(
of tuple: TupleExprElementListSyntax, with newLabel: String
) -> TupleExprElementListSyntax{
guard let firstElement = tuple.first else {
return tuple
}
return tuple.replacing(
childAt: 0, with: firstElement.withLabel(.identifier(newLabel)))
}
public struct ColorLiteralMacro: ExpressionMacro {
public static func expand(
_ macro: MacroExpansionExprSyntax, in context: inout MacroExpansionContext
) -> ExprSyntax {
let argList = replaceFirstLabel(
of: macro.argumentList, with: "_colorLiteralRed"
)
let initSyntax: ExprSyntax = ".init(\(argList))"
if let leadingTrivia = macro.leadingTrivia {
return initSyntax.withLeadingTrivia(leadingTrivia)
}
return initSyntax
}
}
public struct FileIDMacro: ExpressionMacro {
public static func expand(
_ macro: MacroExpansionExprSyntax, in context: inout MacroExpansionContext
) -> ExprSyntax {
let fileLiteral: ExprSyntax = #""\#(context.moduleName)/\#(context.fileName)""#
if let leadingTrivia = macro.leadingTrivia {
return fileLiteral.withLeadingTrivia(leadingTrivia)
}
return fileLiteral
}
}
public struct StringifyMacro: ExpressionMacro {
public static func expand(
_ macro: MacroExpansionExprSyntax, in context: inout MacroExpansionContext
) -> ExprSyntax {
guard let argument = macro.argumentList.first?.expression else {
// FIXME: Create a diagnostic for the missing argument?
return ExprSyntax(macro)
}
return "(\(argument), \(StringLiteralExprSyntax(content: argument.description)))"
}
}