Swift Syntax Comment Trivia - Expected prefixes

Hello! I am working on a project that does some automatic code generation using SwiftSyntax and SwiftSyntaxBuilder. As part of this project, I want to put in a comment at the top of the file warning users to not modify the file and make it obvious that the code was automatically generated. I was trying to use the .lineComment(String) static member of the Trivia (or TriviaPiece) types and I expected that the comment would automatically be prefixed with the expected // and space for use in code. (For example, Trivia.lineComment("No comment") would be written as // No Comment when sent through a BasicFormat Object or similar SyntaxRewriter). I was surprised to find that this is not the case and was wondering before I write an issue on GitHub whether this behavior is intentional or a bug. If it is intentional, I'm not entirely sure if I'm missing something regarding this to more easily generate these comments.

At the moment my comment generation consists of constructing the comment in the leadingTrivia of the syntax node that appears after the comment. For example:

VariableDeclSyntax(leadingTrivia: [.newlines(2), .lineComment("// These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently."), .newlines(1)], modifiers: [DeclModifierSyntax(name: .keyword(.private)), DeclModifierSyntax(name: .keyword(.static))], .let, name: PatternSyntax(IdentifierPatternSyntax(identifier: "decoder")), initializer: InitializerClauseSyntax(value: ExprSyntax(stringLiteral: "\(configuration.decoderExpression)")))

outputs


// These members are always generated irrespective of the contents of the generated files. They are intended to exclusively centralize code symbols that would otherwise be repeated frequently.
private static let decoder = JSONDecoder()

in this project (with example data having been added).

Answered by DTS Engineer in 794316022

I think you might have more luck asking this over on Swift Forums, and specifically in the Development > Macros topic area. While you’re not creating a macro per se, a lot of folks with deeper Swift Syntax experience hang out there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I think you might have more luck asking this over on Swift Forums, and specifically in the Development > Macros topic area. While you’re not creating a macro per se, a lot of folks with deeper Swift Syntax experience hang out there.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Swift Syntax Comment Trivia - Expected prefixes
 
 
Q