Limits of macro automatic formatting

I'm having trouble determining the rules for macro auto-formatting. I'm not sure what's expected and what's a bug. For example, modifying the stringify macro this way:

    return ExprSyntax(
        FunctionCallExprSyntax(
            callee: ClosureExprSyntax {
                """
                    (\(argument),\(literal: argument.description))
                    (\(argument),\(literal: argument.description))
                """
            }
        )

(I believe this is what's required to have a macro return multiple statements.)

The result is:

{
    (a + b, "a + b")
    (a + b,"a + b")
}()

Even though the inputs are the same, the trivia is different. Is this expected behavior? (It's making it very hard to write tests. I think I'm just going to turn formatting off.)

EDIT: I did not realize how much pain turning off formatting was going to cause. I assumed that things like IfConfigClauseListSyntax using the result builder would automatically insert required newlines; is that still trivia?

6 Likes

I don't have an answer for the formatting, and have experienced this many times myself, but these little formatting quirks (which can change between SwiftSyntax versions) was a major reason we made our macro testing library. It allows you to just re-record all expansions (instead of copy-pasting or manually updating strings) and then you can manually inspect whether any formatting differences were significant or not.

Not saying that it wouldn't be nice to have these formatting quirks ironed out, but it is one possible workaround.

7 Likes