StanfordSpezi / SpeziAccount

The Spezi Account module to enable login and signup functionality
https://swiftpackageindex.com/StanfordSpezi/SpeziAccount/documentation/
MIT License
5 stars 5 forks source link

Macro support for Computed Knowledge Source conformance for AccountKey #64

Open Supereg opened 2 months ago

Supereg commented 2 months ago

Problem

62 introduced the @AccountKey and @KeyEntry macros to simplify the process of defining new account keys. Some account keys need more flexibility and adopt the ComputedKnowledgeSource or OptionalComputedKnowledgeSource protocol.

This can currently done by manually declaring a manual conformance using an extension. However, that exposes the internal name of the generated AccountKey implementation.

Here is an example how such a conformance currently looks like for the userId key: https://github.com/StanfordSpezi/SpeziAccount/blob/6b38140b2404146412f3a761491f29ec4acf66cb/Sources/SpeziAccount/AccountValue/Keys/UserIdKey.swift#L142-L152

Solution

Introduce a more refined approach to introduce this conformance. This is not trivial as Macros generally cannot introduce extensions. However, you can create an attached extension macro (attaching a macro to a type that declares an extension to a protocol). A possible design could look like this.

Create an attached extension macro (e.g., @ComputedKeyExtension). This macro is placed by the @AccountKey macro onto the generated AccountKey type. The @ComputedKeyExtension macro receives a closure that is executed in the compute implementation. It doesn't need to be generic, as it is strongly typed to the AccountStorage. How the @AccountKey macro decides to generate the additional macro might need some experimentation what works best. Maybe as an additional trailing closure (maybe a bit weird?). Maybe we can also add another macro to the property that the @AccountKey macro could parse, however, this might not be allowed by the Swift macro system.

Additional context

No response

Code of Conduct