Apply annotation to type with a macro

I'd like to have a macro that applies some annotations to a type. For example,

@Service
final class UserService { ... }

would expand to...

@MainActor
@Observable
final class UserService { ... }

I couldn't figure out a way to do this - is it possible?

When I tried to do this ~6 months ago, there wasn’t any way. So what I did was use the macro to verify that the correct attributes were applied (as they are visible to the macro), and apply an error to the declaration (I think you can add a fixit too).

1 Like

Got it - that's a decent solution.

It would be nice if we could apply annotations with macros someday, it would make them more composable - just like how we can compose multiple protocols into one via protocol Foo: Bar, Baz

I think the issue is recursion/Turing-completeness. If that could be prevented or avoided, it might be possible to implement something like that.

1 Like