Why are SwiftSyntax's `DiagnosticMessage`, `NoteMessage`, etc., protocols?

I can't find documentation motivating why these types are protocols instead of simple structs, but I find it a bit cumbersome to write one-off conformances just to add diagnostics to a macro. Is there a particular reason why these are protocols and why there aren't simple, type-erased versions of them that we can reach for without having to write out a conformance?


They are protocols because it makes it flexible to create parameterized error messages. For example, in SwiftParserDiagnostics/ParserDiagnosticMessages.swift we have quite a few types that conform to ParserError (which conforms to DiagnosticMessage) and many of these have a member that parameterizes the error message.

That way, we separate the emission of error messages from their textual representation, which should make it easier to localize the error messages if we want to do so in the future.

If you just want to create an error message based on a string, there is MacroExpansionErrorMessage, which you might find useful.


Is MacroNoteMessage: NoteMessage missing?

Oh, yes, it is. Would you mind filing an issue on GitHub - apple/swift-syntax: A set of Swift libraries for parsing, inspecting, generating, and transforming Swift source code. or opening a PR to add it?

Done! Add MacroExpansionNoteMessage by stephencelis · Pull Request #2330 · apple/swift-syntax · GitHub

1 Like