Recommended way of converting to String in SwiftSyntax

Hi there,

I've been using SwiftSyntax recently to write a code generation tool, and the guys at pointfree.co have great videos about this usage.

But one of the weird things that strikes me as dangerous is how to convert a Syntax node to a String. I see it being done via string interpolation:

"\(node)"

I always have the feeling that using interpolation to get what in practice is a string description of a type is not really safe. Maybe the output is changed or is just intended for debugging purposes. In any case it doesn't feel like an official API.

What are your thoughts on this? Maybe somebody from the SwiftSyntax project can chime in to give us some guidance? That would be appreciated.

Cheers.

I originally wrote this. At the time, it seemed like a good idea that the description property of a Syntax node would be the original source text, but now I feel like it'd be more useful to have separate, explicit methods for writing source text to a stream, e.g.

func writeSourceText<Stream: TextOutputStream>(to stream: inout Stream) {...}

As of now, calling .description or using string interpolation will give you the source text that the Syntax tree corresponds to. I don't know if it would be worth renaming that, because that's now breaking existing expectations.

Having a explicit method would make it clearer but the current situation works. If it were documented somehow I feel that it would be enough.

Thanks!

1 Like

Everything (nodes, trivia, etc) conforms to TextOutputStreamable for this purpose:

node.write(to: &stream)

I generally use it wrapped in a convenience function though, since I rarely need to write more than one root node to the same stream.

1 Like
Terms of Service

Privacy Policy

Cookie Policy