Skip to content

Enable combining multiple macros on a single type#1935

Open
kperryua wants to merge 3 commits intoswiftlang:experimental/new-codablefrom
kperryua:new-codable/combining-macros
Open

Enable combining multiple macros on a single type#1935
kperryua wants to merge 3 commits intoswiftlang:experimental/new-codablefrom
kperryua:new-codable/combining-macros

Conversation

@kperryua
Copy link
Copy Markdown
Contributor

This PR enables combining multiple Codable macros on a single type

Motivation:

At present it isn't actually possible to add @JSONCodable and @CommonCodable to a single type. It isn't even possible to add @JSONEncodable and @JSONDecodable separately. The core restriction lies in the fact that each macro takes upon itself the responsibility to generate the CodingFields type and its implementation. We need to make the macros "share" that responsibility.

Modifications:

We're working with limited information in a macro, especially regarding other macros attached to the same type—basically just its name.

  • We use "Codable", "Encodable", and "Decodable" suffixes on the macros as hints for the intention of the macro.
  • We allow only the first (lexically) codable macro to generate a CodingFields "base" type.
  • If there's only one format being implemented, that CodingFields type also becomes the type that will be used directly by the implementation. If there are multiple, then separate "wrapper" structs will be created that defer to that core type. This is to allow each format macro to conform to separate CodingField protocols like JSONOptimizedCodingField.

Result:

@JSONCodable and @CommonCodable can now be combined in any order. Same for @JSONEncodable and @JSONDecodable (for a result identical to just @JSONCodable).

The important parts I care about most are the shared macro interfaces and the resulting output. The actual implementation of the macros could be improved and deduplicated a fair bit. That's not my top priority right now though.

Testing:

Macro expansion verification, including improved diagnostics in swift testing.
Macro integration testing to ensure the generated code works correctly.

@kperryua kperryua added the new-codable Related to new Swift (de)serialization APIs label Apr 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

new-codable Related to new Swift (de)serialization APIs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant