Expression macro with attached Comments

I have made an expression macro, like #URL. Now I want to add comments before expression or after it for convenience. I want to generate RGB values for color components generated from hex in comment.

public struct ColorValuesFromHexMacro: HexExpressionMacro {
    public static func colorExpressionSyntax(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) -> SwiftSyntax.ExprSyntax {
      var expr: SwiftSyntax.ExprSyntax = "ColorValues(r: \(raw: red), g: \(raw: green), b: \(raw: blue), a: \(raw: alpha))"
//      expr.trailingTrivia = .lineComment("\\\\ \(red), g: \(green), b: \(blue), a: \(alpha)")
      
      return expr
    }
}

When using trailingTrivia I get compiler error: Extra tokens after expression in macro expansion. There are also no suitable initializers in ExprSyntax.

Is it even possible?

If the code you pasted here is verbatim what you used (without the line being commented out), it looks like the comments you're adding are preceded by backslashes instead of forward slashes. Instead of this:

.lineComment("\\\\ ...")

You want this:

.lineComment("// ...")

Since this is an expression macro, you may also need to force a newline after the comment. I'm not sure if the compiler's macro substitution will do that for you.

Oh, silly mistake. Thank you for pointing it out.
Compiler macro just paste the provided string as is, so it is done by adding
= .lineComment(" // r: \(red), g: \(green), b: \(blue), a: \(alpha)")

1 Like