How to use macros to generate comments

I hope to generate some comments simultaneously when using macros to generate code, but I haven't found any macros related to comments. Does macros support comment generation currently?

1 Like

On every token or syntax node, you can call .with(...) which allows you to set certain properties of it. Two of these properties are leadingTrivia and trailingTrivia which allow you to attach whitespace or comments to a node. For example:

StructDeclSyntax(...)
            .with(\.leadingTrivia, .lineComment("My Struct"))

Alternatively, you can also rely on the implicit string parser that transforms Swift code into syntax nodes. In macro implementations, this often looks like:

static func expansion(...) throws -> [ExtensionDeclSyntax] {
    [
        try ExtensionDeclSyntax("""
            /// Conformance to ``MyProtocol``
            extension \(type): MyProtocol {
                // ...
            }
        """
    ]
}

3 Likes

Thank you for your detailed answer, it's very useful.